我正在尝试实现一个ArrayList,它保存用户输入的详细信息并显示它们。该代码可以正常工作,但构造函数从main调用两次,并从StudentDetails类调用两次。有没有办法让它只调用一次?
这是具有主要方法调用StudentDetails类的对象的Student类和具有ArrayList的StudentDetails类。

public class Student2 {

  public static void main(String[] args) {
     StudentDetails sd1 = new StudentDetails();
     sd1.input();
     sd1.display();
  }

  class StudentDetails {
    int marks;
    String names;
    List<StudentDetails> sd = new ArrayList<>();

    public int getMarks() {
        return marks;
    }

    public void setMarks(int marks) {
        this.marks = marks;
    }

    public String getNames() {
        return names;
    }

    public void setNames(String names) {
        this.names = names;
    }

    public StudentDetails() {
        System.out.println("Program Started");
    }

    public void input() {
        int no;
        StudentDetails sDetails = new StudentDetails();
        System.out.println("How many students?");
        Scanner sc = new Scanner(System.in);
        no = sc.nextInt();

        for (int i = 0; i < no; i++) {
            System.out.println("Enter name of student" + (i + 1));
            sDetails.setNames(sc.next());
            System.out.println("Enter marks for same student");
            sDetails.setMarks(sc.nextInt());
            sd.add(sDetails);
        }
    }

    public void display() {
        for (int i = 0; i < sd.size(); i++) {
            System.out.println("The name of student" + " " + (i + 1) + " " + "is" + " " + sd.get(i).getNames()
                    + " and marks are" + " " + sd.get(i).getMarks());
        }
    }
}

最佳答案

您调用它两次(创建两个StudentDetails实例),但实际上这还不够。您的input()方法应该多次调用它-每次循环迭代一次-因为您要将这些对象添加到列表中,并且您不想多次添加相同的对象。

通过将maininput()设为静态方法并将display()更改为静态变量,可以避免在sd创建对象。

public static void main(String[] args) {
   StudentDetails.input();
   StudentDetails.display();
}

...
static List<StudentDetails> sd = new ArrayList<>();
...
public static void input() {
    ...
    for (int i = 0; i < no; i++) {
        StudentDetails sDetails = new StudentDetails();
        System.out.println("Enter name of student" + (i + 1));
        sDetails.setNames(sc.next());
        System.out.println("Enter marks for same student");
        sDetails.setMarks(sc.nextInt());
        sd.add(sDetails);
    }
    ...
}

public static void display() {
    ...
}

10-04 17:50