我想實現一個ArrayList,它保存用戶輸入的細節並顯示它們。代碼工作正常,但構造函數從主要和從StudentDetails類的其他調用兩次。有沒有辦法讓它只打一次? 這裏是Student類具有調用StudentDetails類的對象的主方法和具有ArrayList的StudentDetails類。構造函數被調用TWice
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 SD1 =新StudentDetails()一個附加的類;','StudentDetails sDetails =新StudentDetails();'。是的,它被調用兩次... – SomeJavaGuy
提示:一個構造函數只能調用一次。將您的打印輸出更改爲包含* this *,並且您將意識到您的構造函數被稱爲「兩次」,因爲您正在創建**兩個** StudentDetails對象。 – GhostCat
我知道我正在創建兩個對象。有沒有一種解決方法可以使它與單個對象一起工作? –