Where should I place this command in my code?
Item item = new Item();
I should put this inside my loop do-while
so that it keeps on creating a new Item
class depends on the user if how many times they want to input another product.
The problem is whenever i put that command inside my do-while
, it cannot find the symbol item
based on the codes at the bottom of my program. So where i should put it?
My code:
public static void main(String[] args) {
Scanner scan = new Scanner(System. in );
String prompt, id;
int z = 0, choice, x = 999;
int iprice;
String icode;
String iname;
class Item {
public int price;
public String code;
public String name;
}
ArrayList<Item> cart = new ArrayList<Item>(0);
do {
System.out.print("\nItem Code: ");
icode = scan.next();
System.out.print("Item Name: ");
iname = scan.next();
System.out.print("Item Price: ");
iprice = scan.nextInt();
item.code = icode;
item.name = iname;
item.price = iprice;
cart.add(item);
System.out.print("\tInput another? Y/N? ");
prompt = scan.next();
} while (prompt.equals("y"));
System.out.println("\nWhat do you want to do?");
System.out.println("\n1. Purchase Item ");
System.out.println("2. List of Products ");
System.out.println("3. Exit Program ");
System.out.print("\n\tChoice: ");
choice = scan.nextInt();
if (choice == 1) {
System.out.println("\nItem Code: ");
id = scan.next();
if (item.code.equals(id)) {
System.out.println("Item Name: " + item.name);
System.out.println("Item Price: " + item.price);
}
}
}
You should probably declare the variable outside the loop with:
Item item;
And then you should initialize it at the very beginning of the loop:
item = new Item();
This way the variable is visible troughout the class, so you won´t get the error you metioned...
Also, this basically means that you are creating a new object in each loop iteration, and you are assigning this new object to the variable item
you previously declared, so your user can create as many different items as he wants...
Note that, although you are overriding the variable item
in each iteration, you won´t lose the object previously attached to the variable item
, because you are adding a reference to that object into your ArrayList<Item> cart
when you do cart.add(item)
...
You may want to read this article about declaration of classes and objects in Java, scopes and so on...
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments