3

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());
}

en11をループカウンターに変更したいと思います。これは可能ですか?

4

3 に答える 3

11

配列を使ってみる

 en[i].setName (scanner.next ());
于 2012-08-02T20:34:39.957 に答える
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) があります。それぞれが 1 回の反復に対応できます。他の変数に基づいて変数の名前を変更する方法はありません。

于 2012-08-02T20:37:54.813 に答える
1

いいえ、Java で変数を使用してパラメーターの名前を変更することはできません。他のユーザーが提案したように、en オブジェクトの配列を作成し、ループ カウンターを使用して個々のオブジェクトにアクセスします。この方法は、はるかにクリーンで慣用的です。

于 2012-08-02T20:37:10.393 に答える