Hello I am trying to figure out how I can use a while loop to construct an object and ask the user if they want to construct another one and add 1 to the name. For instance I am creating an Employee class that I want the name of the objects to be e1, e2.... Basically I have this but I want to add 1 to the name each time the user says yes and create a new object:

       int i = 1;
while(answer =="y")

Employee (emp + i) = new Employee();

So the first time it would be e1, then the next would be e2 and so on. I know this is isnt nice looking but I just want to know what I need to use to get something like this to work.

Edited by Nick Evan: Fixed formatting

6 Years
Discussion Span
Last Post by NormR1

What you are asking for can't be done like that, but arrays were invented to solve that problem. You can't dynamically create e1, e2, e3, but you can create an array e[] and dynamically assign e[0], e[1], e[2] etc.
ps To test two Strings for containing the same sequence of characters you need the equals method. == tests for them being exactly the same object. So instead of

while(answer =="y") // almost always false, answer isn't the same object as "y"

you need

while (answer.equals("y")) // true if answer consists of  a single character 'y'

want to add 1 to the name each time the user says yes and create a new object:

You can't create new variable names when executing a program. Names are defined when you type them in.
There are other ways to have "collections" of objects. For example save the reference to the newly created object in an array or an arraylist. Then you can access them by using an index.

If you do want to create names to associate with objects, look at using a Map. The key would be your new name and the value would be the reference to the new object.
aMap.put("e1", new Employee());

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.