【发布时间】:2017-04-11 11:46:13
【问题描述】:
我正在尝试创建一个程序,该程序将读取格式如下的 .txt 文件:
学生总数
名称
得分1
分数2
得分3
名称
得分1
等等
我目前的代码是这样的:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.*;
public class Project5 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter file name: ");
String filename = in.nextLine();
File filetest = new File(filename);
Scanner imp = new Scanner(filetest);
List<String> studentList = new ArrayList<String>();
List<Integer> studentScores = new ArrayList<Integer>();
String total = imp.nextLine();
int i = 0;
try {
while (imp.hasNext()) {
if (imp.hasNextInt()) {
studentScores.add(imp.nextInt());
} else {
studentList.add(imp.nextLine());
i++;
}
}
} finally {
System.out.println("Name\t\tScore1\t\tScore2\t\tScore3");
System.out.println("-------------------------------------------------------");
System.out.println(total);
System.out.println(studentList.get(0) + "\t" + studentScores.subList(0, 3));
System.out.println(studentList.get(2) + studentScores.subList(3, 6));
System.out.println(studentList.get(4) + studentScores.subList(6, 9));
System.out.println(studentList.get(6) + studentScores.subList(9, 12));
imp.close();
in.close();
}
}
}
我想在控制台中显示的格式是列出姓名,然后是学生收到的三个分数,然后重复一遍,但现在它是硬编码的,只是针对当前学生的数量,而且无论有多少学生,我都需要它能够创建输出。
当前输出:
总计
名称 [score1 score2 score3]
等等
期望的输出:
总计
名称 score1 score2 score3 (而不是用 [] )
等等
非常感谢任何帮助。
【问题讨论】:
标签: java text-files java.util.scanner