3

So I have this code, where en1 is an instance of a object.

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

I would like to change the 1 on en1 to the loop counter. Is this possible?

1

3 Answers 3

11

Try using an array

 en[i].setName (scanner.next ());
Sign up to request clarification or add additional context in comments.

2 Comments

Can I use an array of an object?
You can use an array of references to objects.
2

Your best bet is to use an Array and have each element correspond to the iteration of the loop.

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

The array in my example will have 20 elements (0 through 19). Each one can correspond to a single iteration. There is no way to change the name of a variable based on other variables.

2 Comments

en is not a string. It is an object.
A object from a class. Here is the class code. Sorry the text is in spanish. pastebin.com/gUCWRRgK
1

No, you cannot change the names of parameters using variables in Java. Like the other user suggested, make an array of en objects and access each individual object using the loop counter. This way is much cleaner and idiomatic.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.