0

I want to build a program that only stops scanning for strings until after I input "0" in the console, how do I do that?

I assume I can use do while loop, but I don't know what to put in the while() condition.

    Scanner scan = new Scanner(System.in);

    do {

        String line = scan.nextLine(); 

        //do stuff

    } while(); //what do i put in here to stop scanning after i input "0"

Thanks in advance, I'm new to Java and OOP in general.

AB3
  • 67
  • 6
  • Put in there some condition ot check if `line` is different from "0". You need to declare the variable outside of the loop tho. – Amongalen Mar 20 '20 at 12:12
  • Does this answer your question? [How do I exit a while loop in Java?](https://stackoverflow.com/questions/7951690/how-do-i-exit-a-while-loop-in-java) – steviestickman Mar 20 '20 at 12:13
  • can you provide an example for exactly what you want – Abhinav Chauhan Mar 20 '20 at 12:46
  • Does this answer your question? [How to end a while Loop via user input](https://stackoverflow.com/questions/18975208/how-to-end-a-while-loop-via-user-input) – Joshua Wade Mar 20 '20 at 15:35

2 Answers2

1

You can use a while loop instead of a do-while loop. Define a String that will be initialized inside the while loop. On each iteration we assign the String to Scanner#nextLine and check if that line is not equal to 0. If it is, the while-loop prevents iteration.

        Scanner scan = new Scanner(System.in);

        String line;

        while (!(line = scan.nextLine()).equals("0")) {
            System.out.println("line: " + line);
        }
Jason
  • 5,154
  • 2
  • 12
  • 22
1

You don't have to use any loop , as you said you want to stop input when 0 is pressed by default for nextLine() the input stops when user press the enter key because it is the delimiter , so just change the delimiter

Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("0");   //regex
String s = scanner.next(); // no matter what user enters the s will contain the input before 0
Abhinav Chauhan
  • 1,304
  • 1
  • 7
  • 24
  • The user said **until I stop scanning for Strings** so it is implied they want multiple String values, meaning some type of looping mechanics is required. Not a singular line. – Jason Mar 20 '20 at 12:43