在Java中的for循环中创建几个新对象

msc*_*c87 1 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 ();
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请帮我完成这段代码.

Dan*_*n W 7

你覆盖它们是因为你Bill在每个循环上创建一个新的并且永远不会将它们保存在任何地方.我相信你想把它们添加到你的ArrayList:

首先,您应该为您的类型添加一个类型ArrayList:

ArrayList<Bill> ary = new ArrayList<Bill>();
Run Code Online (Sandbox Code Playgroud)

然后,在您收到用户关于是否添加新内容的输入之前Bill,您应该将当前的一个添加到此列表中:

...
System.out.println("user Last name:");
bill1.setLname(input.nextLine());
ary.add(bill1);
...
Run Code Online (Sandbox Code Playgroud)