2017-02-01 2 views
-1

ArrayListでオブジェクトを動的に命名する方法を教えてください。だから私は、この持っている:Java ArrayListの動的名前オブジェクト

 optionNum = input.nextInt(); 
     switch (optionNum) { 
      case 1: //Customer Information Retrieval 
        int i = 0; 
        System.out.println("What is the customer ID"); 
         customerId = input.next(); 
         newCustomer.setcustomerId(customerId); 
        System.out.println("What is the customer first name?"); 
         firstName = input.next(); 
         newCustomer.setfirstName(firstName); 
        System.out.println("What is the customer last name?"); 
         lastName = input.next(); 
         newCustomer.setlastName(lastName); 
        System.out.println("What is the customer age?"); 
         age = input.nextInt(); 
         newCustomer.setAge(age); 
        System.out.println("What is the customer income?"); 
         income = input.nextDouble(); 
         newCustomer.setIncome(income); 
        System.out.println("What is the customer credit score?"); 
         creditScore= input.nextInt(); 
         newCustomer.setcreditScore(creditScore); 
        newCustomer.Attributes(customerId, firstName, lastName, age, income, creditScore); 
        customers.add(i, newCustomer); 
        i++; 
        break; 

をループしながら、それがdo内にあるが、私は新しい顧客を追加するたびに、それは同じ情報を持つ2人の顧客と私を残し、古い顧客を上書きします。ループの繰り返しごとに新しいオブジェクトを作成するにはどうすればいいですか?

+0

あなたは十分なコードを共有していませんが、新しいオブジェクトを作成するには、コンストラクタをどこかで呼び出すために 'new'キーワードを使用する必要があります。 –

答えて

0

newCustomerオブジェクトを外側ではなくケースブロック内に作成します。基本的に同じオブジェクトを上書きしているため、以前の値は上書きされますが、新しいエントリもリスト内で毎回作成されます。

+0

ありがとうございます!!!!!!!!!!! – Oluwatosin

0

1)顧客前ループを宣言する: 顧客newCustomer = null; 2)ループ内で顧客インスタンスを作成し、newCustomerオブジェクトに設定します。 newCustomer = new Customer(); 3)お客様のオブジェクトに記入してください 4)お客様のリストに追加してください

関連する問題