所以我有一个输出的变量ID
1
2
3
4
5
我只想获取第一个数字1并将其添加为student1.id 第二个数字为student2.id,依此类推。
当前,如果我打印出Student1.id,我会得到
1
2
3
4
5
我将如何处理?我尝试做一个for循环,但它说这是不可迭代的。
public class main {
/**
* Reads a text file containing student data and uses this to populate the student objects
*
* @param filename Path to the student data file to be read
* @return Whether the file was read successfully
*/
public static boolean readFile(String filename) { File file = new File(filename);
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
String[] words = scanner.nextLine().split(",");
addStudent(words[0],words[1],words[2],words[3],words[4],words[5],words[6],words[7],words[8]); // TODO: Finish adding the parameters
}
scanner.close();
} catch (FileNotFoundException e) { System.out.println("Failed to read file");
}
return true;
}
static void addStudent(String id, String firstName, String lastName, String mathsMark1, String mathsMark2, String mathsMark3, String englishMark1, String englishMark2, String englishMark3) {
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
Student student4 = new Student();
Student student5 = new Student();
student1.id = id;
student1.firstname = firstName;
student1.lastname = lastName;
System.out.println(student1.id);
}
答案 0 :(得分:0)
您正在使用split(",")
。输入为1,2,3,4,5
或将代码更改为split(" ")
。
答案 1 :(得分:0)
假设您的文件包含用逗号分隔的整数元素。我将创建一个List<Student>
并将words
存储到这样的每个列表元素
List<Student> students = new Arraylist<>();
for (int i = 0; i < words.length; i++) {
Student s1 = new Student();
s1.id = Intger.parseInt(words[i]); // since words is String[]
students.add(s1)
}
在您的代码段中,您创建了5个Student
对象,但仅使用第一个对象。
要输出,只需像这样使用for循环...
for (Student student: students) {
System.out.println(student.id);
}