ItemOrder item = new ItemOrder(inputName, price, quantity); cart.add(item);
How can I make it so that instead of creating an object called item, I can create an object with the same name as inputName (see complete code bellow)? Thus far the only logical path I could think of was prompting for the name first, then creating an empty item object with solely the name in it and setting the values afterwards, but it still has the same inherent problem of creating an object with a user defined name so it can be searched in an Array list. Otherwise my arrayList will try to add a new object item continuously and the ArrayList.contains(object) method won't work for searching.
Items are objects that have a name, and a value. I created a subclass called ItemOrder which defines the quantity. The classes for Item and ItemOrder are not included as they are simple constructors.
As usual any and all help is much appreciated.
Cheers
Master Zeddicus
import java.util.*;
public class ShoppingCart {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean keepGoing = true;
String inputName, input;
int quantity;
double price;
ArrayList cart = new ArrayList();
while(keepGoing)
{
System.out.println("What name would you like to give your item?");
inputName = keyboard.nextLine();
System.out.println("What is the market price of a " + inputName + "?");
price = keyboard.nextDouble();
while (price <= 0)
{
System.out.println("You cannot have a negative or 0 value for an article");
System.out.println("What is the market price of a " + inputName + "?");
price = keyboard.nextDouble();
}
System.out.println("How many " + inputName + " would you like to order?" );
quantity = keyboard.nextInt();
while (quantity < 0)
{
System.out.println("You cannot have a negative quanitity in your cart");
System.out.println("How many " + inputName + " would you like to order?" );
quantity = keyboard.nextInt();
}
ItemOrder item = new ItemOrder(inputName, price, quantity);
cart.add(item);
System.out.println("Would you like to create another item? (Y/N)");
input = keyboard.nextLine();
while(!input.equalsIgnoreCase("N") && !input.equalsIgnoreCase("Y"))
{
System.out.println("Error: That is not a valid response, please enter Y or N");
System.out.println("Would you like to create another item? (Y/N)");
input = keyboard.nextLine();
}
if (input.equalsIgnoreCase("Y"))
keepGoing = true;
else
keepGoing = false;
}
}
}

New Topic/Question
Reply




MultiQuote




|