Reputation: 815
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.
Upvotes: 3
Views: 281
Reputation: 8338
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
}
Upvotes: 1
Reputation: 24
You could use a try-catch block inside the while loop, and if you catch an exception just keep going to the next iteration. It is not the best solution but for you case it should work.
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) {}
Upvotes: -1
Reputation: 1583
try this.
String line;
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
try {
while((line = read.readLine()) != null){
line.replaceAll(" ","");
if(line.length()>0){
n = Integer.parseInt(line);
}
}
}
catch (IOException e) {}
Upvotes: 0
Reputation: 20520
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.
Upvotes: 1