I'm writing my solution for a problem which involves, among other things, parsing a string which contains numbers entered by the user, separated with spaces and then storing them as integers.
I'm not sure why I get a numberformat exception, when I'm using the nextLine()
method to first accept the string (including spaces) and then using the split
method to separate out the integers. What's still weird is that the code has worked in a different problem before, but not here apparently.
Here's the code, and the exception message:
package algorithms.Warmup;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Created by manishgiri on 4/8/15.
*/
public class ChocolateFeastTest {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter number of test cases:");
int T = sc.nextInt();
ArrayList<Integer> result = new ArrayList<>(T);
for(int i = 0; i < T; i++) {
int[] numbers = new int[3];
System.out.println("Enter N, C, M separated by spaces");
String next = sc.nextLine();
String[] nextSplit = next.split(" ");
int item;
for(int p = 0; p < 3; p++) {
item = Integer.parseInt(nextSplit[p]);
numbers[p] = item;
}
int N = numbers[0];
int C = numbers[1];
int M = numbers[2];
System.out.println(N + C + M);
}
}
}
And the exception messages:
Enter number of test cases:
2
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
Enter N, C, M separated by spaces
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 algorithms.Warmup.ChocolateFeastTest.main(ChocolateFeastTest.java:32)
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:140)
Process finished with exit code 1
On tracing the exception, it looks like the error occurs in the line when I use Integer.parseInt()
, but even before that, why doesn't the code read in the numbers (with spaces) in the first place? ie: this line doesn't work:
String next = sc.nextLine()
I'd appreciate any help!