[英]Creating a program to read through Integers and Strings in Java
I am trying to create a program that will read from a .txt file that is formatted as such: 我正在尝试创建一个程序,该程序将从格式如下的.txt文件读取:
Total number of students 学生总人数
Name 名称
Score1 得分1
Score2 得分2
Score3 得分3
Name 名称
Score1 得分1
etc 等等
My current code is this: 我当前的代码是这样的:
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();
}
}
}
The format I want to display into the console is to list the name, then the three scores that student received, and to repeat it, but right now it is hard-coded just for the amount of students that are currently there, and I need it to be able to create output regardless of how many students there are. 我要在控制台中显示的格式是列出姓名,然后列出学生获得的三个分数,然后重复该格式,但是现在,它只是针对当前在校学生的数量进行了硬编码,因此我需要无论有多少学生,它都能够创建输出。
Current output: 电流输出:
Total 总
Name [score1 score2 score3] 名称[score1 score2 score3]
etc 等等
Desired output: 所需的输出:
Total 总
Name score1 score2 score3 (rather than with the [] ) 名称score1 score2 score3(而不是[])
etc 等等
Any help is greatly appreciated. 任何帮助是极大的赞赏。
The toString
method of a List
will return it in that format. List
的toString
方法将以该格式返回它。 If you want a different format, you can do this with a Stream
: 如果您想要其他格式,可以使用Stream
:
System.out.println(studentList.get(2) + studentScores.subList(3, 6).stream().collect(Collectors.joining(" ");
Health warning: if this is for a school assignment where the use of Stream
s may get you accused of plagiarism, you will need to concatenate the elements yourself the long way. 健康警告:如果这是为了学校作业,而使用Stream
可能使您被指控窃,则您需要自己将这些元素连接很长一段路。
This is the efficient solution that uses a StringBuilder
and no Lists
. 这是使用StringBuilder
而不使用Lists
的高效解决方案。 A StringBuilder
is basically a class that helps you to build string. StringBuilder
是一个可帮助您构建字符串的类。 Pretty straightforward. 非常简单。
// 1024 means that the initial capacity of sb is 1024
StringBuilder sb = new StringBuilder(1024);
try {
while (imp.hasNext()) {
if (imp.hasNextInt()) {
// add the scores and "tab" character to the string
sb.append("\t").append(imp.nextInt());
} else {
// add the name to the string
sb.append("\n").append(imp.nextLine());
i++; // btw.. why are you doing this i++ ??
}
}
} finally {
System.out.println("Name\t\tScore1\t\tScore2\t\tScore3");
System.out.println("-------------------------------------------------------");
System.out.println(total);
System.out.println(sb.toString());
imp.close();
in.close();
}
If you do want to use an arraylist then I suggest iterate through the arraylist like an array and print out the scores. 如果您确实想使用数组列表,那么我建议像数组一样遍历数组列表并打印出分数。
More structural way to do this : 更具结构性的方法:
public class Project5 {
static class Student {
private String name;
private final List<Integer> scores;
private int total;
public Student() {
scores = new ArrayList<>();
total = 0;
}
public void setName(String name) {
this.name = name;
}
public void addScore(int score) {
scores.add(score);
total += score;
}
public String getName() {
return name;
}
public List<Integer> getScores() {
return scores;
}
public int getTotal() {
return total;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(name).append('\t').append(total);
for (Integer score : scores) {
sb.append('\t').append(score);
}
return sb.toString();
}
}
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter file name: ");
String filename = in.nextLine();
in.close();
File filetest = new File(filename);
Scanner imp = new Scanner(filetest);
int total = Integer.parseInt(imp.nextLine());
System.out.println("Name\tTotal\tScore 1\tScore 2\tScore 3");
for (int i = 0; i < total && imp.hasNextLine(); i++) {
Student student = new Student();
student.setName(imp.nextLine());
while (imp.hasNextInt()) {
student.addScore(imp.nextInt());
}
if (imp.hasNext()) {
imp.nextLine();
}
System.out.println(student);
}
imp.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.