【发布时间】:2014-12-05 00:30:33
【问题描述】:
好的,这里需要一些帮助。我正在获取一个带有数据(info.txt)的输入文件并将该数据存储在一个数组中。我已经做到了这一点,但现在我需要使用我刚刚制作的数组将数据输出到格式良好的表格中。我觉得自己很愚蠢,但我一生都无法弄清楚如何使用数组和 for 循环来做到这一点。我已经创建了 for 循环并告诉它如何制作表格,但我认为它不正确。当我在当前状态下运行程序时,它给了我一个错误,我不知道为什么或如何修复它.数组不是强制性的,但是它的编码方式是教授想要的语法方式。是的,这是家庭作业,我擦洗了我的教科书和幻灯片,空手而归,摸不着头脑。有人可以帮忙吗?下面是数据和代码以及表格的外观。谢谢!
数据(info.txt 输入文件。):
9
Andy Borders
200
250
400
John Smith
120
220
330
Alvin Smith
225
300
278
Mike Borell
250
250
500
Jim Jones
325
325
155
Robert Fennel
200
150
350
Craig Fenner
230
220
480
Bill Johnson
120
150
220
Brent Garland
220
240
350
主类:
import java.util.Scanner;
import java.io.*;
public class Project5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the file name: ");
String fileName = in.nextLine();
try {
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
String SnumStudents = inputFile.nextLine();
int numStudents = Integer.parseInt(SnumStudents);
Student [] studentList = new Student[numStudents];
for (int i = 0; i <=numStudents; i++)
{
String line = inputFile.nextLine();
String score1 = inputFile.nextLine();
String score2 = inputFile.nextLine();
String score3 = inputFile.nextLine();
String total = null;
studentList [i] = new Student(line, Integer.parseInt(score1), Integer.parseInt(score2), Integer.parseInt(score3), Integer.parseInt(total));
}
System.out.println("Name\t\tScore1\tScore2\tScore3\tTotal");
System.out.println("---------------------------------------------");
for (int i=0; i< studentList.length;i++){
System.out.println(studentList[i].getName() + "\t" + studentList[i].getScore1() + "\t" + studentList[i].getScore2() + "\t" + studentList[i].getScore3() + "\t" + studentList[i].getTotal());
}
System.out.println("---------------------------------------------");
inputFile.close();
} catch (IOException e) {
System.out.println("There was a problem reading from " + fileName);
}
finally {
}
in.close();
}
}
学生班:
public class Student {
private String name;
private int score1;
private int score2;
private int score3;
private int total;
public Student(String n, int s1, int s2, int s3, int t){
name = n;
score1 = s1;
score2 = s2;
score3 = s3;
total = t;
t = s1 + s2 + s3;
}
public String getName(){
return name;
}
public int getScore1(){
return score1;
}
public int getScore2(){
return score2;
}
public int getScore3(){
return score3;
}
public int getTotal(){
return total;
}
}
表格(这个应该都是排好的,不知道为什么这里排成这样。):
姓名 Score1 Score2 Score3 Total
安迪·博德斯 200 250 400 850
这里的其他玩家格式相同。
本班学生总数:7 全班平均总分:778 John Borell 获得的最高分数为:1000 比尔·约翰逊的最低分数是:490(每个都应该在不同的行上)
【问题讨论】: