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 with while, but it does not stop even when the word "exit" is inputted. Any ideas how to fix this? Thanks.
public void read(Scanner scanner){
while(3<4){
String in = scanner.nextLine();
Scanner scanner_2 = new Scanner(in);
String name = null;
if(scanner_2.hasNext()){
//create and add the user to the user container class
name = scanner_2.next();
System.out.println(name);
}
if(name == exit)
//stop or break the while loop
}
}
name == exit
is wrong.You want
or
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 typicallyoverriden
in the class by the developer.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
Not as below way
The main reason for making "exit" as first value is, if name is
null
then it will not fireNullPointerException
but if we placename
as first object for comparing then if name is null then it will fires thatNullPointerException
exception, so make sure this thing any time in future.Assuming
String exit = "exit";
is declared somewhere ar the class level:checks whether the object referenced by
name
and the object referenced byexit
are the same. What you want it whether the value of the object referenced byname
and the value of the object referenced byexit
are the same.You do that by
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.
Actually he code can be further improved as:
But I think you are learning and this may be a bit too much when you are learning.
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 :)