2012-05-10 3 views
1

Я хочу создать несколько объектов из класса в цикле for. но я не знаю, как его кодировать. То, что я написал, создает новый объект, но он перезаписывает предыдущий объект.Создайте несколько новых объектов внутри цикла for в Java

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(); 
       } 
      } 
     } 
    } 
} 

, пожалуйста, помогите мне заполнить этот код.

+1

Что именно вы пытаетесь сделать? –

+0

Я хочу добавить новые объекты (bill2, bill3, ...) в эту базу данных, но мой код записывает новый объект поверх предыдущего. Я хочу сохранить всю информацию об объектах в моей базе данных. – msc87

+0

@ msc87 Полезно, если вы отметите ответ, который помог решить проблему как принятый ответ (плюс вы получите 2 кармы)! – jbranchaud

ответ

1

Вы не использовали ArrayList, вам необходимо добавить объекты Bill's в конец цикла for.

ary.add(bill1); 

и добавить тип к вашему ArrayList

ArrayList<Bill> ary = new ArrayList<Bill>(); 
7

Вы перекрывая их, потому что вы создаете новый Bill на каждом цикле и никогда не экономим их в любом месте. Я считаю, что вы хотите, чтобы добавить их в ваш ArrayList:

Во-первых, вы должны добавить тип к вашему ArrayList:

ArrayList<Bill> ary = new ArrayList<Bill>(); 

Тогда, прежде чем вы получите ввод от пользователя на том или нет, чтобы добавить новый Bill, вы должны добавить текущий к этому списку:

... 
System.out.println("user Last name:"); 
bill1.setLname(input.nextLine()); 
ary.add(bill1); 
... 
+0

сделал то, что вы предложили, и теперь я могу сохранить новые объекты, но есть и другая проблема ... Я не могу получить информацию об объектах. например; System.out.println (bill1.getFname (ary.get (index))) – msc87

+1

@ msc87 Вместо этого используйте 'ary.get (index) .getFname()' (хотя я не могу быть уверен, не видя информацию класса Bill. –

+0

Я положил класс Bill, и я сделал то, что вы сказали, но он возвращает эту ошибку: Исключение в потоке «main» java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 \t at java.util.ArrayList.RangeCheck (Неизвестный источник) \t at java.util.ArrayList.get (Неизвестный источник) \t at assginment1_version2.Client.main (Client.java:46) – msc87

0

Это класс Билл .....

package assginment1_version2; 

public class Bill { 

/** 
* Attributes of a bill 
*/ 
private String firstName; 
private String lastName; 
private int paymentDeadline; 
private int paymentCode; 
private int billCode; 

/** 
* Attribute of Bill Class 
*/ 

     private static int BillCounter=0; 

/** 
* Methods of Bill class 
* @return number of users 
*/ 
/*public static int getBillCounter(){ 
    return BillCounter; 
}*/ 


/** 
* Class Constructor 
* @param Fname is the first name of user 
* @param Lname is the last name of user 
* @param Pdeadline is the deadline of paying the bill 
* @param Pcode introduces the payment uniquely 
* @param Bcode introduces the bill uniquely 
*/ 
    public Bill(){ 
     BillCounter++; 
    } 

/** 
* FirstName methods 
* method to set FirstName 
* @param n is the input of setname method as a user name 
*/ 
public void setFname (String n){ 
    firstName=n; 
} 
// method to get FirstName 
public String getFname(){ 
    return firstName; 
} 


/** 
* LastName methods 
* method to set LastName 
*/ 
public void setLname (String m){ 
    lastName=m; 
} 
// method to get LastName 
public String getLname(){ 
    return lastName; 
} 


/** 
* PaymentDeadline methods 
* method to set PaymentDeadline  
*/ 
public void setPaymentDeadline(int m){ 
    paymentDeadline= m; 
} 
//method to get PaymentDeadline 
public int getPaymentDeadline(){ 
    return paymentDeadline; 
} 

/* 
* PaymentCode methods 
* Method to set PaymentCode 
*/ 
public void setPaymentCode (int m){ 
    paymentCode=m; 
} 
//method to get PaymentCode 
public int getPaymentCode(){ 
    return paymentCode; 
} 

/* 
* Methods of BillCode 
* method to set BillCode 
*/ 
public void setBcode(int Bcode){ 
    billCode=Bcode; 
} 
//method to get BillCode 
public int getBcode(){ 
    return billCode; 
} 
} 
Смежные вопросы