I'm trying to code shopping cart program, using Arraylist. I want to make this --> when the user types 1 or Add item(s), it adds the (quantity, name, price) of the item that user wanted to add. But, I get errors in the very last part, since the "cart" cannot be resolved. I know this is because "ArrayList cart = new ArrayList(i);" is in the for loops, but I don't know how to fix this. Also, am I using Arraylist correctly? I've been struggling for 3 days and still not sure..
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class item {
public item(int quantity, String name, double price) {
}
public static void main(String[] args)
{
item();
}//end main
public static void item()
{
Scanner myinput = new Scanner(System.in);
int total ;
int quantity;
String name = null;
double price;
String option;
System.out.println("How many kind of items do you have?");
total = myinput.nextInt();
for (int i = 1; i<=total; i )
{
System.out.println("Please type the quantity of your item(s) (ex : If you have 2 shirts, please type 2)");
quantity = myinput.nextInt();
if (quantity == 0)
{
break;
}
System.out.println("Please type the name of your item(s)");
name = myinput.next();
System.out.println("Please type the price of your item(s)");
price = myinput.nextDouble();
ArrayList<item> cart = new ArrayList<item>(i);
}
System.out.println("Please choose one option below \n1) Add item(s) \n2) Remove item(s) \n3) View Cart \n4) Checkout \n5) Exit");
option = myinput.next();
switch(option)
{
case "1" , "Add item(s)":
System.out.print("Please type the name of your item(s)");
name = myinput.next();
System.out.print("Please type the price of your item(s)");
price = myinput.nextDouble();
System.out.print("Please type the quantity of your item(s)");
quantity = myinput.nextInt();
cart.add(new item(quantity, name, price)); //gets error in "cart"
System.out.println(Arrays.toString(cart)); //gets error in "cart"**strong text**
break;
}
}//end item
}//end class
CodePudding user response:
In your switch
statement, you refer to a variable called cart
. But no such variable exists at that point.
The only cart
you have is defined within your for
loop. So each time through the loop, you instantiate a new cart
(a new ArrayList
object), and immediately discard it. At loop’s end, any variables defined within the loop, and never shared outside the loop, instantly become candidates for garbage-collection, become unreachable to you, and will eventually be deleted by the garbage collector.
At the point the flow-of-control reaches your switch
, no cart
object remains available to your code.