我想在for循環中從一個類創建幾個對象。但我不知道如何編碼。我寫的內容創建了一個新對象,但它覆蓋了前一個對象。在Java for循環中創建幾個新對象
package assginment1_version4;
import java.util.*;
public class Client {
public static void main (String[] args) {
System.out.println ("this is a bill database");
System.out.println ("add a user?(Y/N)");
Scanner input = new Scanner(System.in);
String answer = input.nextLine();
ArrayList ary = new ArrayList();
for (int i=1 ; i < 100; i++) {
if (answer.equalsIgnoreCase("y")) {
Bill bill1 = new Bill();
System.out.println("user first name:");
bill1.setFname (input.nextLine());
System.out.println("user Last name:");
bill1.setLname (input.nextLine());
System.out.println ("add a user?(Y/N)");
answer = input.nextLine();
} else if (answer.equalsIgnoreCase ("n")) {
if (Bill.getBillCounter() == 0) {
System.out.println ("the Database is empty");
break;
} else {
System.out.println ("Number of Users: "
+ Bill.getBillCounter());
break;
}
} else {
while (!answer.equalsIgnoreCase ("n")
&& !answer.equalsIgnoreCase ("y")) {
System.out.println ("add a user?(Y/N)");
answer = input.nextLine();
}
}
}
}
}
請幫我完成這段代碼。
你究竟想要做什麼? –
我想向這個數據庫添加新的對象(bill2,bill3,...),但是我的代碼將新對象寫入到前一個對象中。我想將所有對象信息保留在我的數據庫中。 – msc87
@ msc87如果您將幫助解決問題的答案標記爲已接受的答案(加上您獲得2個業力),這很有幫助! – jbranchaud