Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict EOF on newline java

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.

like image 759
Tahmid Ali Avatar asked Sep 20 '26 03:09

Tahmid Ali


2 Answers

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
}
like image 149
Alex K Avatar answered Sep 22 '26 17:09

Alex K


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.

like image 42
chiastic-security Avatar answered Sep 22 '26 17:09

chiastic-security



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!