I got the proper EOF criteria in Java with this question and it is doing fine. But the problem occurred when a program required an input of a blank line after each input case. The following code works fine for EOF.
String line;
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
try {
while((line = read.readLine()) != null){
n = Integer.parseInt(line);
}
}
catch (IOException e) {}
But the problem is, I got to solve a problem where after input of each case, a blank new line is inputted. As a result I am getting a NumberFormatException and this is expected too. I have tried all that I could do including try-catch() mechanism.
It would be great if I have a code that doesn't terminate or throw exception on a blank line input.
Probably the best way to do this would be to just check the length of the input before doing anything. So:
if(line.length() > 0) {
//do whatever you want
}
You can check whether
"".equals(line.trim())
before trying to convert it to an integer.
But an even better way would be to use a Scanner, and then use Scanner.nextInt() to get the next token. That will deal with the blanks automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With