I am continuously getting a NumberFormatException
for my string and I am not sure why. It seems to work fine when compiled, and I cannot figure out what is wrong with the code to cause it to not run.
Here is an screenshot of what is showing.
As stated above, I cannot find any reason why my code is not working. It all looks right to me and ran fine until the last few methods it seems.
public static int loadArray(int[] numbers) {
System.out.print("Enter the file name: ");
String fileName = keyboard.nextLine();
File file = new File(fileName);
BufferedReader br;
String line;
int index = 0;
try {
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
numbers[index++] = Integer.parseInt(line);
if(index > 150) {
System.out.println("Max read size: 150 elements. Terminating execution with status code 1.");
System.exit(0);
}
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file " + fileName + ". Terminating execution with status code 1.");
System.exit(0);
}catch(IOException ie){
System.out.println("Unable to read data from file. Terminating execution with status code 1.");
System.exit(0);
}
return index;
}
I want to use my switch to be able to find different values in the array, but I cannot even get the array file to load properly.
You are getting NumberFormatException during the app work because this is RuntimeException and it's designed to work so.
The problem with your solution that you're trying to parse int from the whole line in file.
"123, 23, -2, 17" is not the one integer.
So you should do the following:
instead of numbers[index++] = Integer.parseInt(line);
String[] ints = line.split(", ");
for(i = 0; i < ints.length; i++ ){
numbers[index++] = Integer.parseInt(ints[i]);
}