Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple object in array (java)

I want to create objects using the result from Scanner and add them to an array.

However, each time I ask for user input for the second time, it just overwrites the first object.

How can I add multiple objects to the array?

Here's my code:

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++;
    }
}
like image 722
Phil_oneil Avatar asked Mar 26 '26 07:03

Phil_oneil


1 Answers

Your loop is not actually overwriting the first value. It is just creating a new ArrayList every time you loop through.

You should create one ArrayList and continously add to it.

ex.

ArrayList<Game> games = new ArrayList<Game>();
while(...) {
   ...
   games.add(...);
   ...
}

Couple notes:

  • You do not have to create a new Scanner for every scan you can just use the same one (Also initialize it outside the loop like the array list).

  • i=i++ could just be i++, i++ increments the variable i, it is different than i + 1. It is equivalent to i = i + 1.

  • It is good practice to use the List interface for the ArrayList variable so that your code will work the same regardless of which List implementation you use.

like image 155
Simba Avatar answered Mar 27 '26 21:03

Simba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!