2

The code works for the most part, but if I type "No way" it still stops the loop. Should I set it up a different way or use a length function ? Everything I've searched on breaking a loop used integers.

See the code below:

import java.util.Scanner;

public class CarryOn {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        
        while (true) {
            System.out.println("Shall we carry on?");
            String answer = String.valueOf(scanner.next());
            
            if (answer.equalsIgnoreCase("no")){
                break;
            }
        }
    }
}
Braiam
  • 4,345
  • 11
  • 47
  • 69

2 Answers2

2
scanner.next()

only reads a single token. No way is two tokens: No and way.

Use scanner.nextLine() instead, if you want to read the whole line.

Andy Turner
  • 122,430
  • 10
  • 138
  • 216
2

Using .next in this case only stores "no" in "no way". Use .nextLine instead:

Scanner scanner = new Scanner(System.in);
while (true) {
     System.out.println("Shall we carry on?");
     String answer = String.valueOf(scanner.nextLine());
     if (answer.equalsIgnoreCase("no")){
          break;
     }
}

Output:

Shall we carry on?
no way
Shall we carry on?
no

Check this post for more information.

Majed Badawi
  • 16,831
  • 3
  • 12
  • 27