public static int askingAmount() {
System.out.println("How many persons are there in your company?");
Scanner amountS = new Scanner(System.in);
amount = amountS.nextInt();
System.out.println(amount);
amountS.close();
return amount;
}
public static void makingPersons() {
for (int i=0 ; i<amount ; i++) {
int personNumber=0;
Person person[i] = new Person(); //<--- The problem
System.out.println("person");
}
}
在第一种方法中,我试图询问用户他们有多少人,然后返还金额。在第二个我想创建相同数量的Person对象,并使用变量“i”将其命名为person1,person2,person3,但我没有让它工作。有线索吗?
答案 0 :(得分:1)
将循环外的数组定义为类成员:
Person[] person;
然后在askingAmount
中初始化它:
person = new Person[amount];
在循环内部执行:
person[i] = new Person();
答案 1 :(得分:1)
public static void makingPersons() {
Person[] persons = new Person[amount];
for (int i=0 ; i<amount ; i++) {
int personNumber=0;
persons[i] = new Person(); //<--- The solution
System.out.println("person");
}
}
答案 2 :(得分:0)
你必须从循环中启动一个Person类型的数组,然后用新的实例填充它,如下所示:
public static void makingPersons() {
Person[] person = new Person[amount];
for (int i=0 ; i<amount ; i++) {
int personNumber=0;
person[i] = new Person();
System.out.println("person");
}
}