0

So basically, I'm trying to keep taking input from the user and printing it line by line, until he's done, then I'll print done. Problem is, the code works just fine until I press double Enter/Return, it's supposed to print DONE however it returns an ArrayIndexOutOfBoundsException @ 1. So what am I doing wrong?

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));   
    String line;
    while((line = br.readLine()) != null) {
        String[] tmp = line.split(" ");
        System.out.println(tmp[0] + " " + tmp[1]);
    }

    System.out.println("DONE");
  • On double enter, at least one line is `""`; so you split it by `" "` which yields an array of `{ "" }` and then you try and print the second element (and there isn't one). – Elliott Frisch Feb 26 '17 at 12:51
  • @ElliottFrisch ahh yes I see your point, but isn't it supposed to NOT enter the body of the loop from the first place? I mean the line will be equal to NULL won't it? – thelili700 Feb 26 '17 at 12:54
  • `null` is not `""`. You could add `if (line.isEmpty()) break;` before your `split`. – Elliott Frisch Feb 26 '17 at 12:54
  • @ElliottFrisch Ok I get it now. But when will the read line be equal to NULL? – thelili700 Feb 26 '17 at 12:56
  • After someone closes `System.in`; ctrl-z in Windows or ctrl-d everywhere else. That usage is more common with a `File` (which has a more firm "end"). – Elliott Frisch Feb 26 '17 at 12:57
  • @ElliottFrisch Thanks Elliott! That really helped. – thelili700 Feb 26 '17 at 13:00

0 Answers0