how can I create numerous objects inside a loop and store each cycle inside a different location of memory? For example, I am writing a test program for my shopping bag program, and I would like to add Candy and Milk to my shopping bag. When I type these objects in for the user input, and print it out, it only prints out the last object. Which is milk. I have thought about using array list, but I do not know how to add the object name,price,quantity to that array list of an object.
Here is my code if you would prefer to look at it:
import java.util.ArrayList;
import java.util.Scanner;
public class TestDriver
{
public static void main (String[]args)
{
ArrayList<ShoppingBag>list= new ArrayList<ShoppingBag>();
Scanner sc = new Scanner(System.in);
Boolean answer=true;
ShoppingBag shop= new ShoppingBag(6);
while(answer==true)
{
System.out.println("Enter the name of the items(Enter None to stop): ");
String name=sc.next();
if(name.equalsIgnoreCase("none"))
{
answer=false;
}
else
{
shop.setName(name);
System.out.println("Enter count: ");
int count=sc.nextInt();
shop.setNumberOfItems(count);
System.out.println("Enter cost(unit price): ");
float subTotal= sc.nextFloat();
shop.setSubtotal(subTotal);
}
}
System.out.println(shop.toString());
}
}
Aucun commentaire:
Enregistrer un commentaire