gpt4 book ai didi

java - 数组中的多个对象(java)

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:11:28 25 4
gpt4 key购买 nike

我想使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com