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.
if(name == exit)
is wront thats true.
But make sure while comparing two string, when one string is constant e.g. "exit" then make sure that it comes first while comparing.
i.e. it should be compared as
if ("exit".equals(name))
Not as below way
if (name.equals("exit"))
The main reason for making "exit" as first value is, if name is null then it will not fire NullPointerException but if we place name as first object for comparing then if name is null then it will fires that NullPointerException exception, so make sure this thing any time in future.
name == exit is wrong.
You want
name.equals(exit)
or
name.equals("exit")
depending on whether exit is a variable or a string literal, respectively. In Java, == means reference equality (e.g Are these two references pointing to the same address in memory), whereas .equals means object equivalence, which is typically overriden in the class by the developer.
Amirs's answer is 100% correct. In addition, use true inside the while loop and, I think it is better to use else... if statement in this case. More readable, thats why :)