I have written this simple loop for collecting integers from the standard input. How can I modify this loop, so that it stops when the user enters a blank line? Right now the loop keeps going on, ignoring empty lines, it only stops when i insert a letter (for example).
I would like it to work both as a prompt, but also as a standard input redirect.
Thanks in advance.
import java.util.Scanner;
public class example{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
boolean auth = true;
do {
try{
int num = in.nextInt();
in.nextLine();
System.out.println(num);
} catch(Exception e){
System.out.println(e);
in.nextLine();
auth = false;
}
} while(auth);
in.close();
}
}
CodePudding user response:
Use next() instead of nextLine(). nextLine() reads inputs including the space between the words. A space will be read as empty String. If you are using next(), it will not read blank lines at all. It reads the input till the space.
CodePudding user response:
You could use in.nextLine() instead of in.nextInt(), and then use the isEmpty() function to check if it is empty and Integer.parseInt() to convert it back to an int. You can do it more efficiently but this should suffice
int num = 0;
String input = in.nextLine();
if(input.isEmpty()){
auth = false;
}
else{
num = Integer.parseInt(input);
System.out.println(num);
}
