1

I'm a student and I decided to try out some of the problem sets at UVa Online Judge to help improve my skill. I ran into a brick wall on the first problem. After fighting compiler errors (I finally found some vague guidelines for submitting Java code in their forums), I've now graduated to "Wrong Answer" status.

To get to the point -- if I don't surround this while loop with a try/catch, it generates a NumberFormatException at runtime on input string "" on the call to Integer.parseInt(). That makes sense, except if input is "" then it is null and should not enter the loop.

I've tried getting rid of split(" ") and use a StringTokenizer, but that generates an wrong index exception.

The program works fine until I end input by hitting Enter. That's when the error generates. If I surround the loop with a try/catch, there's no errors, but the console seems to throw in an additional line break, and I believe that's the source of my "Wrong Answer" status.

What am I doing wrong?

public static void main(String[] args){
     Scanner kb = new Scanner(System.in);
     String input;
     String[] temp;
     int i, j;

     while( (input = kb.nextLine()) != null ){
        temp = input.split(" ");
        i = Integer.parseInt(temp[0]);
        j = Integer.parseInt(temp[1]);
        solve(i, j);
     }
}
spedsal
  • 113
  • 1
  • 5

2 Answers2

5

It is unclear why you're expecting kb.nextLine() to return null when an empty line is entered. You should compare against "" instead of null.

You should also check kb.hasNextLine() before calling kb.nextLine().

public static void main(String[] args){
     Scanner kb = new Scanner(System.in);
     String[] temp;
     int i, j;

     while (kb.hasNextLine()) {
        String input = kb.nextLine();
        if (input.equals("")) break;
        temp = input.split(" ");
        i = Integer.parseInt(temp[0]);
        j = Integer.parseInt(temp[1]);
        solve(i, j);
     }
}
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

There is a next line so it won't return null its just that the line is empty and thus "".

mark-cs
  • 4,677
  • 24
  • 32