Java 从扫描程序向ArrayList添加多个数据类型元素

Java 从扫描程序向ArrayList添加多个数据类型元素,java,arraylist,Java,Arraylist,尝试从输入文件向ArrayList中添加一些学生元素(姓名、年龄、gpa)。我试过研究资料,觉得这里有个语法错误,尽管我不确定。我在Stack Exchange上发布了一些问题,这些问题被认为是一般性的,并被鼓励添加评论和非常具体的内容。从输入文件向ArrayList添加元素的正确语法是什么?请让我知道,如果有什么我可以做或补充,使我的问题更清楚。以下是我的工作内容: public void readFile() throws IOException { String name;

尝试从输入文件向ArrayList中添加一些学生元素(姓名、年龄、gpa)。我试过研究资料,觉得这里有个语法错误,尽管我不确定。我在Stack Exchange上发布了一些问题,这些问题被认为是一般性的,并被鼓励添加评论和非常具体的内容。从输入文件向ArrayList添加元素的正确语法是什么?请让我知道,如果有什么我可以做或补充,使我的问题更清楚。以下是我的工作内容:

public void readFile() throws IOException
{
    String name;
    int age;
    double gpa; // instance variables

    String line;

    PrintWriter ot = new PrintWriter(new FileWriter("output.txt")); //opens the output file

    Scanner sc = new Scanner(new File("Employees.txt"));

    while (sc.hasNextLine()) { 
    //read first line from file 
    name = sc.nextLine();
    students.add(name); // throws error here stating "no suitable method found

    // read next line from file and convert String to int
    line = sc.nextLine();
    age = Integer.parseInt(line);
    students.add(age);

    // read next line from file and convert String to double
    line = sc.nextLine();
    gpa = Double.parseDouble(line);
    students.add(gpa);

    System.out.printf("%s %d %f \n", name, age, gpa);
    ot.printf("%s %d %f \n", name, age, gpa);
   }

我想“学生”就是你所说的ArrayList。ArrayList是特定于类型的,因此您不能像希望的那样执行此操作。但是,您应该创建一个“Student”类,该类的属性为name、age和gpa,然后您可以用Student对象填充ArrayList

创建学生类后,应该是这样的:

while (sc.hasNextLine()) { 
//read first line from file 
name = sc.nextLine();
age = sc.nextLine();
gpa = sc.nextLine();

Student newStudent = new Student(name, age, gpa); //deal with age and gpa parsing inside Student constructor

students.add(newStudent); 

System.out.printf("%s %s %s \n", name, age, gpa);
//should print the same as
System.out.printf("%s %d %f \n", newStudent.name, newStudent.age, newStudent.gpa);

}

它对我非常有效。当输入不在新行(即学生的所有三个属性)中时,给出
NoSuchElementException:No line found
异常。您确定所有数据都以新行开始吗?(而不是每个学生)例如,“Student1\n12\3.5\nStudent2\16\2.88\n…”。但是,我建议使用这种格式:“Student1 12 3.5\n Student2 16 2.88…”非常感谢您的反馈。在我的编辑器中,我必须添加:学生新闻学生=新学生(姓名、年龄、gpa);而不是学生新闻学生=学生(姓名、年龄、gpa);只为任何可能遇到这件事的人。