Java:如何使用用户输入的数据声明未定义数量的对象?

时间:2015-09-17 23:35:16

标签: java object

对于我的作业我想让用户输入项目的名称和价格。但是,它们将无限次地输入,直到使用标记值。我实际上并不知道我是如何做到这一点的。我知道如何使用用户输入声明对象的唯一方法是使用扫描程序,然后将该数据放在构造函数的参数中。但这只会创建一个对象。谢谢!

import java.util.Scanner;
public class Item

{

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);



} 

private String name;
private double price;

public static final double TOLERANCE = 0.0000001;

public Item(String name,double price)
{
    this.name = name;
    this.price = price;
}

public Item()
{
    this("",0.0);
}

public Item(Item other)
{
    this.name = other.name;
    this.price = other.price;
}

public String getName()
{
    return name;
}

public double getPrice()
{
    return price;
}

public void setName(String name)
{
    this.name = name;
}

public void setPrice(double price)
{
    this.price = price;
}

public void input(String n, double item)
{

}

public void show()
{
    // Code to be written by student
}

public String toString()
{
    return "Item: " + name + " Price: " + price;
}

public boolean equals(Object other)
{
    if(other == null)
        return false;
    else if(getClass() != other.getClass())
        return false;
    else
    {
        Item otherItem = (Item)other;
        return(name.equals(otherItem.name)
            && equivalent(price, otherItem.price));
    }

}

private static boolean equivalent(double a, double b)
{
    return ( Math.abs(a - b) <= TOLERANCE );
}
}

2 个答案:

答案 0 :(得分:0)

据我所知,你只想初始化一个obects数组。

首先,您需要初始化一个数组:

int n = scanner.nextInt();  // you may get n in other way 
Item[] items = new items[n]; 

然后你可以用Item的新实例填充它:

for(int i = 0; i < n; i++){
    items[i] = new Item(); //constructor args may be here
}

答案 1 :(得分:0)

要添加未定义数量的对象,最佳选择是List在java中。通过使用您的示例,我在main()方法中添加了一些代码,如下所示:

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);


        List<Item> items = new ArrayList<>();
        while (true) {
            System.out.println("--------------------------------");
            System.out.print("Enter item name :: ");
            String name = input.next();
            System.out.print("Enter item price :: ");
            while (!input.hasNextDouble()) {
                System.err.println("Invalid Price (Double) eg. 300");
                System.out.print("Enter item price :: ");
                input.next();
            }
            double price = input.nextDouble();
            Item item = new Item(name, price); //creating object by passing value in constructor
            items.add(item); //adding object in list
            System.out.println("Do you want to add more items ? 'Y'=>Yes or 'N'=>No ");
            String ans = input.next();
            if ("N".equalsIgnoreCase(ans)) {
                break;
            }

        }
        //To retrive item object list
        for (Item i : items) {
            System.out.println(i);
        }

    }