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


Probably the best way to do this is to just check the length of the input before doing anything. So:



if(line.length() > 0) {
    //do whatever you want
}

      

+1


source


You can check,

"".equals(line.trim())

      



before trying to convert it to an integer.

But an even better way is to use Scanner

and then use Scanner.nextInt()

to get the next token. This will automatically handle spaces.

+1


source


try it.

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) {} 

      

0


source


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







All Articles