我正在使一个学生项目分配系统从txt文件读取。这将读取文件并为它们提供最佳项目。之前,我曾尝试在与学生有关的信息(姓名,电子邮件和ID)的单独一行上做出所有项目选择,并且确实起作用。但是,我尝试将它们全部放在一行中,当我看到没有选择四个项目的人时,它就跳过了。这是txt文件:
7
Allan,A a.allan@outlook.ac.uk 53027 1 3 4 2
Brown,B b.brown@outlook.ac.uk 45696 1 2 3 4
Craig,C c.craig@outlook.ac.uk 45667 2 1 4 3
Douglas,D d.douglas@outlook.ac.uk 52981 3 4 1 2
Edward,E e.edward@outlook.ac.uk 45048 3
Findlay,F f.findlay@outlook.ac.uk 46904 2 1 3
Graham,G g.graham@outlook.ac.uk 58733 2 4
最高的数字“ 7”是学生人数,长数字是ID,其他数字是项目编号。当调试器到达Edward'E的第一个项目“ 3”的唯一选择时,程序会认为他的第二个选择是Findlay,F并导致NumberFormatException错误。这是到目前为止的代码:
public Student(int id,Scanner scanner) {
listOfPreferences=new ArrayList<Project>();
projectID= new ArrayList<Integer>();
setID(id);
String name=scanner.next();
this.setName(name);
String email=scanner.next();
this.setEmail(email);
String ID = scanner.next();
this.setID(id);
//scanner.nextLine();
String preferences=scanner.next();
String totalPreferences[] = preferences.split(" ");
String preferences2=scanner.next();
String totalPreferences2[] = preferences2.split(" ");
String preferences3=scanner.next();
String totalPreferences3[] = preferences3.split(" ");
String preferences4=scanner.next();
String totalPreferences4[] = preferences4.split(" ");
for(String project: totalPreferences)
{
projectID.add(Integer.valueOf(project));
}
for(String project: totalPreferences2)
{
projectID.add(Integer.valueOf(project));
}
for(String project: totalPreferences3)
{
projectID.add(Integer.valueOf(project));
}
for(String project: totalPreferences4)
{
projectID.add(Integer.valueOf(project));
}
}
有人真的可以帮助我吗?
答案 0 :(得分:0)
更改您的方法,以创建可独立处理每一行的代码。假设可以将一行数据放入Student类型的对象中,您将执行以下操作:
private List<Student> students = new ArrayList<>();
for (int i = 0; i < maxLineCount; i++) {
String line = scanner.nextLine();
students.add(processLine(line));
}
public Student processLine(String line) {
// code here to create a data object from each line
// using either String#split(..)
// or using a separate Scanner created for each line and then disposed
return new Student(....); // create your data object from the processed line
}
请注意,尾随数字的数量可能会有所不同,因此您需要使用while (someScanner.hasNextInt())
的while循环来循环浏览这些字符,如果使用扫描仪
例如:
public Student processLine(String line) {
Scanner lineScanner = new Scanner(line);
String name = lineScanner.next();
String email = lineScanner.next();
String id = lineScanner.next();
List<Integer> values = new ArrayList<>();
while(lineScanner.hasNextInt()) {
values.add(lineScanner.nextInt());
}
lineScanner.dispose(); // done with the line scanner
// using data collected above create my data or Student?
return new Student(...);
}
单独的问题:请勿将扫描程序传递到Student构造函数中,因为您不应混用逻辑类(例如Student)和UI(用户界面)代码。取而代之的是给Student提供一个构造器,该构造器使用有意义的数据-名称,电子邮件,ID ....,然后在程序的UI部分中收集数据,并在收集数据时创建Student对象。