Reputation: 67
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.
Upvotes: 0
Views: 1093
Reputation: 1384
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
Upvotes: 1
Reputation: 5246
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);
}
Upvotes: 1