我正在尝试创建一个程序,允许老师从名册中抓取学生,然后将他们随机分组。我计划从文本文件创建一个数组列表,其中包含一堆学生姓名。我需要帮助从文件中提取学生姓名,然后将他们的姓名插入数组列表中。
这里是数组派上用场的地方(其他地方也有,但程序不完整):
try {
System.out.println("Please enter the name of the student that you would like to add to the file as \"Last name, First name\"");
PrintWriter outputStream = new PrintWriter(new FileOutputStream(fileName, true));
Scanner sc = new Scanner(System.in);
String s = sc.next();
outputStream.println(s);
sc.close();
outputStream.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
我还需要在这个程序中涉及几个类,所以我创建了这个类,我的想法是我可以为存档的学生创建一个开放变量。
public class Name {
private String studentName;
public Name() {
}
public Name(String studentName) {
this.studentName = studentName;
}
public String getstudentName() {
return studentName;
}
public void setstudentName(String studentName) {
this.studentName = studentName;
}
}
这是包含一些名称的文本文件,对我来说具有挑战性的部分是名称之间有一个逗号分隔(也许我应该删除它?):
Ospina, Bryan
Patel, Krupa
Preite, Nicholas
Quigley, Kevin
Rubet, Aaron
Said, Abanoub
Sidler, Allen
Thiberge, Daniel
Thota, Raajith
Tripathi, Rashi
Tsang, Johnny
Velovic, Joseph
Victor, Samuel
Whitted-Mckoy, Eric
Wu, Michelle
编辑:压缩代码
最佳答案
使用 Stream,您将无法将其用于作业...
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
import java.util.stream.Collectors;
public class Demo {
public static void main(String[] args) throws IOException {
final String filename = "whatever";
List<Name> list =
Files.lines(Paths.get(filename)) // Strings, lines in the file
.map(line -> line.split(",")) // String[], split by ,
.map(split -> split[1] + split[0]) // String, joined again
.map(Name::new) // Name, make a Name object from String
.collect(Collectors.toList()); // collect into a List<Name
}
public static class Name {
private final String studentName;
public Name(String studentName) {
this.studentName = studentName;
}
public String getstudentName() {
return studentName;
}
}
}
关于java - 如何从 java 中的文本文件创建字符串数组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47566944/