I am receiving the error Exception in thread "main" java.lang.NumberFormatException: For input string: "3 50" in the code below. And I am having a hard time solving it. Could anyone possibly shed some light on what it could be from? From my understanding it usually means the error is in line 3 and line 50 correct?
package report.generator;
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 ReportGenerator
{
public static void main(String[] args)
{
BufferedReader br = null;
BufferedWriter bw = null;
try
{
br = new BufferedReader(new FileReader("C:\\sprocketorders.txt"));
String line;
String element[] = new String[2];
int sum[] = new int[5];
File file = new File ("C:\\sprocketordersreport.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 Sprockets\nTaking Sprockets into the Future\nSales Summary Report\nSprocket Number Total Quantity Sold\n");
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();
}
}
}
}
This program is to take an input from a text file and output the information in a report format.
EDIT: Here is the input file info. After looking at it, it looks like this may be where the problem is coming from. But I'm not entirely sure.
3 50
2 20
2 100
5 15
1 90
5 85
4 300
2 35
3 100
It's not formatting it exactly as it is in the text file. There are more spaces between the integers on the left and those on the right.
Integer.parseInt()最有可能抛出该错误,因为您尝试解析的数字格式不正确,请查看您尝试从中读取的字符串,可能会发现错误,然后
[编辑]该问题似乎来自您的输入文件,其中包含数字的行之间有空行。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.