目前我有一个文本文件,用于存储学生姓名及其考试成绩。文件的格式为姓氏、名字和考试成绩。文本文件中的每个值都以空格分隔。所以该文件看起来类似于:
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的新手,但我正在尝试。
最佳答案
这里的代码:
String[] LastName= line.split(txtSplitBy);
String[] FirstName = line.split(txtSplitBy);
String[] TS = line.split(txtSplitBy);
并不是真正需要的,因为您将行多次拆分以创建 3 个不同的字符串数组,您想要做的是将行拆分一次,然后从数组索引中分配变量,如下所示:
String[] splitLine = line.split(txtSplitBy);
String lastName = splitLine[0]; //first element of array
String firstName = splitLine[1]; //second element of array
String score = splitLine[2]; //third element of array
然后您可以将分数解析为字符串,这将是一个数字,而不是您正在尝试的文字字符串 "TS"
您想要变量名称,因此请省略 "
int i = Integer.parseInt (score);
然后,对于 while 循环中的每次迭代,添加总数并进行计数,然后以这种方式计算平均值。 (或创建一个分数列表)例如:
int total = 0;
int count = 0;
List<Integer> allScores = new ArrayList<Integer>();
while ((line = br.readLine()) != null)
{
String[] splitLine = line.split(txtSplitBy);
String lastName = splitLine[0]; //first element of array
String firstName = splitLine[1]; //second element of array
String score = splitLine[2]; //third element of array
System.out.println("Last Name: " + lastName
+ "\n" +"First Name: " + firstname + "\n" +
"Test Score: " + score + "\n") ;
int i = Integer.parseInt (score);
total += i;
count++;
// Add to List
allScores.add(i);
}
double average = total/count;
循环列表
for( Integer i: allscores)
{
// Do the appropriate code here
}
如果您还需要姓名,您应该创建一个类来保存名字、姓氏和分数,然后将它们添加到您的列表中。
关于java - 读取学生姓名和文本分数的文本文件并计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18177213/