如何在java中从文本文件获取文件输入,然后使用数组列表显示它?

问题描述 投票:0回答:1

当我运行从文本文件获取文件输入然后将此输入保存到数组列表中的程序时,我无法打印信息。我将附上我的 Student 类,这是我用于数组列表的类型。我还将附上包含 main 的类。我将包含文本文件的屏幕截图以及我当前获得的输出。我的目标是将每个学生的信息保存到一个学生对象中,然后将这些对象放入一个数组列表中。然后显示数组列表的内容。 下面是学生班。

public class Student {
      public String Name;
      public int BirthYear;
      public int BirthMonth;
      public int BirthDay;
      public double GPA;

      
       public Student(String Name,int BirthYear, int BirthMonth, int BirthDay,double GPA)
       {
          Name = this.Name;
          BirthYear = this.BirthYear;
          BirthMonth =this.BirthMonth;
          BirthDay=this.BirthDay;
          GPA=this.GPA;
       }
    
    public int Age() {
           Calendar c = Calendar.getInstance();
           if(c.get(Calendar.MONTH)>BirthMonth) {
               return (c.get(Calendar.YEAR)-BirthYear);
           }
           else if(c.get(Calendar.MONTH)<BirthMonth) {
               return (c.get(Calendar.YEAR)-BirthYear)-1;
           }
           else if(c.get(Calendar.MONTH)==BirthMonth) {
               if(c.get(Calendar.DAY_OF_MONTH)>BirthDay) {
                   return(c.get(Calendar.YEAR)-BirthYear)-1;
               }
               else {
                   return(c.get(Calendar.YEAR)-BirthYear);  
               }
           }
           else {
               return 0; 
           }
       }
}

下面是主类

    public class RunStudent {

    public static void main(String[] args) throws FileNotFoundException{
        File inputFile = new File("studentData1");
        Scanner FileIn = new Scanner(inputFile);
        ArrayList<Student> List = new ArrayList<Student>();
        
        FileIn.nextLine();
        while(FileIn.hasNextLine()) {
            String FName, LName;
            FName = FileIn.next();
            LName = FileIn.next();
            int BirthYear = FileIn.nextInt();
            int BirthMonth = FileIn.nextInt();
            int BirthDay = FileIn.nextInt();
            double GPA = FileIn.nextDouble();
            String name = FName + " " + LName;
            Student s = new Student(name, BirthYear, BirthMonth, BirthDay, GPA);
            List.add(s);
        }
        FileIn.close();
        for(int i=0; i<List.size(); i++) {
            System.out.println("Name:" + List.get(i).Name);
            System.out.println("Age:" + List.get(i).Age());
            System.out.println("GPA: " + List.get(i).GPA);
        }

    }

}

This is the text file This is a sample output

我还导入了 java.util.* 和 java.io.* 但它不允许我将其包含在帖子中。

java fileinputstream
1个回答
0
投票

“...我想显示学生姓名、年龄和 GPA”

Student类不保留您提供的信息的原因是构造函数方法中的代码。

您分配的字段不正确。

Name = this.Name;
BirthYear = this.BirthYear;

etc...

翻转这些作业。

this.Name = Name;
© www.soinside.com 2019 - 2024. All rights reserved.