【发布时间】:2013-08-11 22:11:23
【问题描述】:
目前我有存储学生姓名和考试成绩的文本文件。文件的格式是姓氏、名字和考试成绩。文本文件中的每个值都是分开的,但有一个空格。所以文件看起来像这样:
Smith John 85
Swan Emma 75
我已经运行了代码,以便将所有数据打印到控制台,但我无法让它做的是获取所有测试分数,将它们相加,然后找到平均值并打印平均值到控制台。以及打印分数低于平均分 10 分的学生。
现在这是我用来读取信息并将信息打印到控制台的代码。
public class ReadTXT
{
public static void main(String[] args)
{
{
String txtFile = "/Users/Amanda/Desktop/Studentdata.txt";
BufferedReader br = null;
String line = "";
String txtSplitBy = " ";
try {
br = new BufferedReader(new FileReader(txtFile));
while ((line = br.readLine()) != null) {
String[] LastName= line.split(txtSplitBy);
String[] FirstName = line.split(txtSplitBy);
String[] TS = line.split(txtSplitBy);
System.out.println("Last Name: " + LastName[0]
+ "\n" +"First Name: " + FirstName[1] + "\n" +
"Test Score: " + TS [2] + "\n") ;
{
double average = sum / i;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
}
这是我试图用来求平均值的代码。
int i =Integer.parseInt ("TS");
double sum = 0.0;
for (int x = 0; x < i; sum += i++);
{
double average = sum / i;
}
不过,我不断收到此异常:
Exception in thread "main" java.lang.NumberFormatException: For input string: "TS"
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 ReadTXT.main(ReadTXT.java:35)
我是学习java的新手,但我正在努力。
【问题讨论】:
-
请向我们展示您完整的异常消息,因为它通常会告诉您(和我们)究竟出了什么问题。
-
@HovercraftFullOfEels 你在开玩笑吗?这是
java.lang.NumberFormatException: "TS" is not a valid number. -
@tbodt:我发布的不仅仅是为我们,而是为 OP,以便他们认真查看堆栈跟踪。
-
线程“main”java.lang.NumberFormatException 中的异常:对于输入字符串:java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 处 java.lang.Integer.parseInt 处的“TS” (Integer.java:492) 在 java.lang.Integer.parseInt(Integer.java:527) 在 ReadTXT.main(ReadTXT.java:35) Java 结果:1
-
我知道 TS 不是一个有效的数字,所以我试图将其转换为一个数字
标签: java arrays file text average