我不断为我的弦乐器获得一个NumberFormatException
,我不知道为什么。它在编译时似乎工作正常,我无法弄清楚代码有什么问题导致它无法运行。
这是显示内容的屏幕截图。
如上所述,我找不到任何我的代码无效的原因。这一切看起来都对我而且运行良好,直到看起来最后几种方法。
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;
}
我想使用我的开关能够在数组中找到不同的值,但我甚至无法正确加载数组文件。
你在应用程序工作期间得到NumberFormatException,因为这是RuntimeException,它的设计是这样的。
您尝试从文件中的整行解析int的解决方案的问题。
“123,23,-2,17”不是一个整数。所以你应该做以下事情:而不是numbers[index++] = Integer.parseInt(line);
String[] ints = line.split(", ");
for(i = 0; i < ints.length; i++ ){
numbers[index++] = Integer.parseInt(ints[i]);
}
问题是你正在阅读整行。
while ((line = br.readLine()) != null)
您无法根据包含空格的整行解析整数。
你有两个选择:
String[]
传递到loadArray
方法中。loadArray
并按空格分割。然后,您可以迭代该数组的内容,并根据需要将每个数据转换为int。