变量包括名称中的循环计数器

时间:2012-08-02 20:33:26

标签: java

所以我有这个代码,其中en1是一个对象的实例。

for (int i = 0; i < 20; i++) {
    System.out.println("Introduce el nombre de una empresa");
    Scanner scanner = new Scanner(System.in);
    en1.setName(scanner.next());
}

我想将en1上的1更改为循环计数器。这可能吗?

3 个答案:

答案 0 :(得分:11)

尝试使用数组

 en[i].setName (scanner.next ());

答案 1 :(得分:2)

最好的办法是使用一个数组,让每个元素对应循环的迭代。

//Instantiation 
Enterprise[] en = new Enterprise[20];//the number of iterations you need

//You do not have a default constructor, so I would use this to add the "int index"
en[i] = new Enterprise(X); //For each enterprise where "X" is a number for the "int index"


//in the loop
en[i].setName(scanner.next());

我的示例中的数组将包含20个元素(0到19)。每一个都可以对应一次迭代。无法根据其他变量更改变量的名称。

答案 2 :(得分:1)

不,您无法使用Java中的变量更改参数名称。与其他用户建议的一样,创建一个en对象数组并使用循环计数器访问每个单独的对象。这种方式更加清洁和惯用。

相关问题