Java: How to declare an indeterminate number of objects with the data entered by the user?

advertisements

for my assignment I am suppose to have a user input the name and price of items. However, they are to enter in an unlimited amount of times until a sentinel value is used. I don't actually know how I'd go about doing this. The only way I know how to declare an object with user input is to use a scanner and then place that data within the arguments of a constructor. But that would only create a single object. Thanks!

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


As I understood you want just initialize an array of obects.

Firstly you need initialize an array:

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

Then you can fill it with new instances of Item:

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