This works
while (true)
{
key = reader.readLine();
if (key.equals("user")){
person = new Person.User();
doWork(person);
}
else if (key.equals("loser")){
person = new Person.Loser();
doWork(person);
}
else if (key.equals("coder")){
person = new Person.Coder();
doWork(person);
}
else if (key.equals("programmer")){
person = new Person.Programmer();
doWork(person);
}
else
break;
}
}
BUT THIS DOES NOT MARK CORRECTLY
while (true)
{
if (reader.readLine().equals("user")){
person = new Person.User();
doWork(person);
}
else if (reader.readLine().equals("loser")){
person = new Person.Loser();
doWork(person);
}
else if (reader.readLine().equals("coder")){
person = new Person.Coder();
doWork(person);
}
else if (reader.readLine().equals("programmer")){
person = new Person.Programmer();
doWork(person);
}
else
break;
}
}
Difference between the two ? One works and other one does not work.
Resolved
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
20 May 2019, 14:44
I think that you are expecting it to jump directly to the correct line, but that is not how if statements work. They evaluate everything in order until a full true is returned.
So.... the second does not work because reader.readLine waits for user input and then returns a string that is that input. So if the user inputs "coder", the first statement will return false and the next if statement will look for another user input. If you wanted a new coder Person object you would have to input coder three times in a row for that to happen.
0
Henk
21 May 2019, 05:05
so the fact that I specify "else if Reader.readline()" again, will trigger the program to actually wait for a second user input, if the first "statement" wasn't true ? Didn't know that, thank you.
+1
Guadalupe Gagnon
21 May 2019, 13:21
correct!
+2