我的代码使用Netbeans IDE。当我尝试运行它时,我得到了这个错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "3 50"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at spacely.sprockets.broc.east.SpacelySprocketsBrocEast.main(SpacelySprocketsBrocEast.java:32)
我还没能在程序中找出会导致这种情况的错误。我的代码在下面。如果有人能为我指明正确的方向,我将不胜感激。谢谢
package spacely.sprockets.broc.east;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class SpacelySprocketsBrocEast
{
public static void main(String[] args)
{
BufferedReader br = null;
BufferedWriter bw = null;
try
{
br = new BufferedReader(new FileReader("sprocketorders.txt"));
String line;
String element[] = new String[2];
int sum[] = new int[5];
File file = new File ("sprocketorders.txt");
while ((line = br.readLine()) != null)
{
element = line.split(" ");
switch(Integer.parseInt(element[0]))
{
case 1:
sum[0] = sum[0] + Integer.parseInt(element[1]);
break;
case 2:
sum[1] = sum[1] + Integer.parseInt(element[1]);
break;
case 3:
sum[2] = sum[2] + Integer.parseInt(element[1]);
break;
case 4:
sum[3] = sum[3] + Integer.parseInt(element[1]);
break;
case 5:
sum[4] = sum[4] + Integer.parseInt(element[1]);
break;
}
}
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
bw = new BufferedWriter(fw);
bw.write("Spacely SprocketsnTaking Sprockets into the FuturenSales Summary ReportnSprocket Number Total Quantity Soldn");
for(int i = 0; i < sum.length; i++)
bw.write((i + 1) + "t" + sum[i] + "n");
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)
br.close();
if (bw != null)
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
错误消息似乎相当明确。Java不知道如何将3 50
解释为单个整数。
如果您想知道原因,请使用调试器或将print语句放在该行之前。抛出异常之前的最后几张照片应该很有启发性。