Object 使对象在for循环中每次命名都不同

Object 使对象在for循环中每次命名都不同,object,for-loop,names,Object,For Loop,Names,好的,我在为一个新对象创建一个新名称时遇到了一个问题,在它被循环多次之后,代码如下: 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 (t

好的,我在为一个新对象创建一个新名称时遇到了一个问题,在它被循环多次之后,代码如下:

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 #");
    }
}

如果Whatever数据类型的大小是静态的,而不是为每个循环创建新变量,则可以创建一个Whatever数组,并在每个循环后增加索引。

这样单独声明所有Whatever对象会使您很难同时对所有对象执行操作-您希望将它们捆绑在一起,可能在一个数组中。我建议先创建一个数组,然后使用for循环来填充新的内容。

您能解释一下为什么要这样做吗?这似乎是容器类型类的一个很好的用法。工作得非常好。我制作了一个ArrayList并不断向其中添加新对象,因此名称实际上都是从0到x的数字。谢谢