Making an object named differently each time in a for loop

46 Views Asked by At

Alright, I am having a problem creating a new name for a new object after it is looped several times, code below:

Whatever A1 = new Whatever();
Whatever A2 = new Whatever();
Whatever A3 = new Whatever();
Whatever A4 = new Whatever();
Whatever A5 = new Whatever();

Scanner input = new Scanner(System.in);
int in;
while (true) {
    try {
        in = Integer.parseInt(input.nextLine());
        switch (in) {
            case 1:
                Whatever A6 = new Whatever(); 
                /*
                * Name A6 for the first time, then A7 for the second time the
                * loop repeats and so on, until I decide to quite the loop
                */
            break;
        }
    } catch (Exception e) {
        System.out.println("Invalid #");
    }
}
2

There are 2 best solutions below

1
On BEST ANSWER

If the size of the Whatever datatype is static, rather than creating new variables for each loop, you could create an Array of Whatever's and just increment the index after each loop.

0
On

Declaring all your Whatever objects individually like that makes it hard to perform an action on all of them at once - you want to bundle them together, probably in an array. I'd recommend first creating an array and then use a for loop to fill it with new Whatevers.