0
votes

This is the main method of my program. I'm having a problem with the Scanner parsing the variable L instead of space when the nextLine() function is called. The nextInt() works as expected, though. My program crashes trying to parse an empty String with the Integer.parseInt() function.

The first input is an integer specifying the number of lines that will proceed, and the following inputs are space-separated integers.

Scanner s = new Scanner (System.in);
int l = s.nextInt();

for (int i = 0; i < l; i++){
    String space = s.nextLine();
    int x = Integer.parseInt(space.split(" ")[0]);
    int y = Integer.parseInt(space.split(" ")[1]);
    printPrimes(x, y);
    System.out.println();
}

The stack trace is as follows:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Contests.SPOJ.SPOJ2.main(SPOJ2.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
2
Can you share some example input that causes this exception? - Jacob Krall
I have tested with the numbers 2 and 3, upon which the program immediately crashes. The program doesn't let me input the nextLine(). - Blimeo

2 Answers

2
votes

nextInt will NOT consume the following newline character, so the next call to nextLine will be the sole newline character ('\n') left in the input.

Make a call to nextLine before the loop to discard it:

Scanner s = new Scanner (System.in);
int l = s.nextInt();
s.nextLine(); // Discarding the '\n'

for (int i = 0; i < l; i++){
    String space = s.nextLine();
...
1
votes

I fixed your program by adding this line inside the loop:

    s = new Scanner(System.in);

The full listing below:

Scanner s = new Scanner (System.in);
int l = s.nextInt();

for (int i = 0; i < l; i++){
    s = new Scanner(System.in);
    String space = s.nextLine();
    int x = Integer.parseInt(space.split(" ")[0]);
    int y = Integer.parseInt(space.split(" ")[1]);
    printPrimes(x, y);
    System.out.println();
}

And it works as expected.