我已经创建了一个程序并将客户对象分配给客户数组,但是当我尝试获取数组中的对象时它返回 null。我是 Java 的新手,请帮我解决我哪里出错了。
public class Customer {
private String firstname,lastname;
public Customer(String f,String l){
this.firstname = f;
this.lastname = l;
}
public String getFirstName(){
return firstname;
}
public String getLastName(){
return lastname;
}
}
public class Bank {
private Customer [] customers;
private int numberofCustomers;
public Bank(){
customers = new Customer [5];
numberofCustomers = 0;
}
public void addCustomer(String f,String l){
int i = numberofCustomers++;
customers[i] = new Customer(f,l);
}
public int getNumberofCustomer(){
return numberofCustomers;
}
public Customer getCustomerMethod(int index){
return customers[index];
}
}
public class TestAccount {
public static void main (String [] args){
Bank b = new Bank();
b.addCustomer("Test", "LastName");
System.out.print(b.getNumberofCustomer());
System.out.print(b.getCustomerMethod(1));
}
}
最佳答案
数组索引从零 开始。您已在数组中索引 0 的第一个元素处添加了一个客户,您应该使用相同的索引来获取该元素。当前索引 1 处没有任何内容,因此您的代码返回 null
;
System.out.print(b.getCustomerMethod(0));
假设数组大小为 5,则其索引为 0,1,2,3,4 其中 0 是第一个索引,4 是最后一个索引。
在这一行之后 b.addCustomer("Test", "LastName");
你的数组将是:
Array: [Customer("Test", "LastName") , null , null, null, null]
Index: 0 , 1 , 2 , 3 , 4
当您尝试“System.out.print(b.getCustomerMethod(1));”时它返回空值。如您所见,您的数组在索引 1 处为空。
关于java - 在 Java 中将对象分配给数组,它返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15660837/