Stop scanner from reading user input java?

前端 未结 4 619
走了就别回头了
走了就别回头了 2021-01-15 14:35

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

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-15 15:06

    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.

提交回复
热议问题