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,但我没有让它工作。有什么线索吗?
最佳答案
将循环外的数组定义为类成员:
Person[] person;
然后在askingAmount
中初始化它:
person = new Person[amount];
在循环内执行以下操作:
person[i] = new Person();
关于java - 在 for 循环中启动对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22224276/