对象数组实现添加和显示客户信息

public class Customer {
private String name;
private int age;
private boolean flag;//是否有会员卡
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
import java.util.Scanner;
public class CustomerBiz {
//定义一个对象数组
private Customer[] cus = new Customer[30];

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);    
    CustomerBiz biz = new CustomerBiz();
    
    for (int i = 0; i < 2; i++) {
        Customer cus = new Customer();
        System.out.print("请输入名称:");
        //给属性赋值
        cus.setName(sc.next());
        System.out.print("年龄:");
        cus.setAge(sc.nextInt());
        //添加客户对象
        biz.addCustomer(cus);
    }
    //展示
    biz.showCustomers();
}

/**
 * 添加对象
 * @param customer
 */
public void addCustomer(Customer customer){
    for (int i = 0; i < cus.length; i++) {
        if (cus[i]==null) {
            cus[i]=customer;
            break;
        }
    }
}
/**
 * 显示客户信息
 */
public void showCustomers(){
    System.out.println("客户信息:");
    for (Customer customer : cus) {
        if(customer != null){
            System.out.println(customer.getName()+"\t"+customer.getAge()+"\t"+customer.isFlag());
        }
    }       
}

}

猜你喜欢

转载自www.cnblogs.com/rainsnow/p/12188008.html