如何解决:“构造函数 Student(String, String, String, String, String) 未定义”

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

我一直在尝试创建一个程序,让用户输入要注册的学生人数,然后输入他们的凭据,然后填写所有信息后,程序将显示所有提交的凭据。我一直在使用 ArrayList 来存储信息,但无法将所有输入信息添加到 ArrayList 中。我应该在这里做什么?

package randomProject2;

import java.util.Scanner;

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
        
        Scanner scan = new Scanner(System.in);
    
        int x = 0;
        
        System.out.print("Enter the number of students to be registered: ");
        int a = scan.nextInt();
        scan.nextLine();
        
        ArrayList<Student> student = new ArrayList<Student>();
        
        for(int i = 0; i < a; i++) {
            
            System.out.print("Enter Student("+x+")'s First Name: ");
            String fName = scan.nextLine();
                    
            System.out.print("Enter Student("+x+")'s Last Name : ");
            String lName = scan.nextLine();
            
            System.out.print("Enter Student("+x+")'s Year      : ");
            String year = scan.nextLine();
            
            System.out.print("Enter Student("+x+")'s Course    : ");
            String course = scan.nextLine();
            
            System.out.print("Enter Student("+x+")'s Section   : ");
            String section = scan.nextLine();
            
            student.add(new Student(fName, lName, year, course, section)); //EXCEPTION here

        
        }
        
        
    }

}
public class Student {

    private String fName, lName, year, course, section; 
    
    
    Student(String fName, String lName, String year, String course, String section)
    {
        this.fName=fName;
        this.lName=lName;
        this.year=year;
        this.course=course;
        this.section=section;
    }
    
    
    void introduceSelf() 
    {
        System.out.println("Full Name: " + fName + " " + lName);
        System.out.println("Course/Year/Section: " + course + " " + year + " " + section);
        System.out.println("");
    }
}

我已经尝试按照 Eclipse 推荐的方法将 Student.add 更改为 Student.addAll,但仍然会导致错误

java arraylist
1个回答
0
投票

看起来

Student
类与
Main
类位于不同的包中。
Student
构造函数是包私有的,您应该将访问修饰符更改为
public

我还建议在单独的行中创建字段,这样更具可读性和可维护性。

public class Student {

    private String fName;
    private String lName;
    private String year;
    private String course;
    private String section; 
    
    
    public Student( // Constructor is public now
      String fName, 
      String lName, 
      String year, 
      String course, 
      String section) {
        this.fName = fName;
        this.lName = lName;
        this.year = year;
        this.course = course;
        this.section = section;
    }
    ...

}

© www.soinside.com 2019 - 2024. All rights reserved.