Limit EOF on newline java
I got the correct EOF criteria in Java with this question and everything is going well. But the problem arose when the program needed to enter a blank line after each input. The following code works great 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 that I solved the problem where after typing each case an empty newline is entered. As a result, I get a NumberFormatException, which is expected too. I tried everything I could, including the try-catch () mechanism.
It would be great if I had code that doesn't end or throw an exception on empty string input.
+3
source to share
4 answers
You can use a try-catch block inside a while loop and if you catch an exception, just keep going for the next iteration. This is not the best solution, but it should work for you.
String line;
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
try {
while((line = read.readLine()) != null) {
try {
n = Integer.parseInt(line);
//other stuff with n
} catch (NumberFormatException e) {
continue; // do nothing, and move on to the next line
}
}
}
catch (IOException e) {}
-1
source to share