gpt4 book ai didi

java - 构造函数被调用两次

转载 作者:行者123 更新时间:2023-11-30 07:08:27 25 4
gpt4 key购买 nike

我正在尝试实现一个ArrayList,它保存用户输入的详细信息并显示它们。代码工作正常,但构造函数从 main 调用两次,从 StudentDetails 类调用一次。有没有办法让它只调用一次?这是具有调用 StudentDetails 类对象的 main 方法的 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() 方法应该多次调用它 - 每次循环迭代一次 - 因为您要将这些对象添加到列表中,并且您不想多次添加相同的对象。

您可以通过使用 input()display() 静态方法并更改 来避免在 main 处创建对象>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() {
...
}

关于java - 构造函数被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39640246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com