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.