Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将新行上的字符串拆分为单独的变量_Java - Fatal编程技术网

Java 将新行上的字符串拆分为单独的变量

Java 将新行上的字符串拆分为单独的变量,java,Java,所以我有一个变量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 stud

所以我有一个变量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);



}

您正在使用split,。提供输入为1,2,3,4,5或将代码更改为split

假设文件包含以逗号分隔的整数元素。我将创建一个列表,并将单词存储到每个列表元素中,如下所示

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)
}

是的,它们现在只是占位符,它们不是整数更新的字符串,以插入整数元素作为id。顺便说一句,您应该使用getter和setter,而不是使用equals运算符分配id
for (Student student: students) {
    System.out.println(student.id);
}