我想使用 Scanner
的结果创建对象并将它们添加到数组中。
但是,每次我第二次请求用户输入时,它只会覆盖第一个对象。
如何向数组添加多个对象?
这是我的代码:
public void ajoutadd() {
int i=0;
boolean boucle=true;
while(i!=2){
Scanner thegame = new Scanner(System.in);
System.out.print("name: \n");
String jname = lejeu.nextLine();
System.out.print(jname);
Scanner qty = new Scanner(System.in);
System.out.print("qty \n");
int jqty = qty.nextInt();
Scanner cat = new Scanner(System.in);
System.out.print("cat: \n");
String categ = cat.nextLine();
Scanner price = new Scanner(System.in);
System.out.print("price: \n");
int jprice = price.nextInt();
Game agame = new Game(jname,jqty,categ,jprice);
System.out.print(unjeu.Nom);
// creating the array to contain the game(s)
ArrayList<Game> thegame = new ArrayList<Game>();
thegame.add(new Game(jname,jqty,categ,jprice));
// actually only display 1 object that is overwritten
// each time after the loop
System.out.println(thegame);
i=i++;
}
}
最佳答案
您的循环实际上并没有覆盖第一个值。它只是创建一个 new ArrayList
每次循环。
您应该创建一个 ArrayList 并不断地向其添加内容。
例如
ArrayList<Game> games = new ArrayList<Game>();
while(...) {
...
games.add(...);
...
}
注意事项:
您不必创建
new Scanner
对于每个scan
你可以只使用同一个(也可以像数组列表一样在循环外初始化它)。i=i++
可能只是i++
,i++
递增变量 i,它不同于i + 1
.相当于i = i + 1
.最好使用
List
ArrayList
的接口(interface)变量,以便您的代码无论使用哪个List
都可以正常工作您使用的实现。
关于java - 数组中的多个对象(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27477145/