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
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.
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.
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 :)
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.