I am trying to write this method, which keeps reading from the user, until the word \"exit\" is inputted. I tried with a break and for loop; it didn\'t work. I was trying wi
Assuming String exit = "exit";
is declared somewhere ar the class level:
name == exit
checks whether the object referenced by name
and the object referenced by exit
are the same. What you want it whether the value of the object referenced by name
and the value of the object referenced by exit
are the same.
You do that by
if(name.equals(exit))
That said, there are a lot of things that can be improved in the code. I understand you are probably writing this code to learn java, but still some small changes can make the code more readable.
Also the second scanner you are using is not needed at all.
The following code will do the same thing as your code, but is smaller and more readable.
String name = "";
while(!name.equals("exit")) {
if(scanner.hasNext()) {
//create and add the user to the user container class
name = scanner.next();
System.out.println(name);
}
}
Actually he code can be further improved as:
String name = null;
while(scanner.hasNext() && !(name = scanner.next()).equals("exit")) {
System.out.println(name);
}
But I think you are learning and this may be a bit too much when you are learning.