-
Arrays
I'm pretty sure that I'm creating the array correctly but I dont know why the items won't add to the cart. And how would I print what the contents of the array? Please help! thanks:D
package shopping;
// ************************************************** *************
// Shop.java
// Uses the Item class to create items and add them to a shopping
// cart stored in an ArrayList.
// ************************************************** *************
// import ArrayList here
import java.text.NumberFormat;
import java.util.Scanner;
import java.util.ArrayList;
public class Shop {
public static void main(String[] args) {
//Declare and instantiate a variable cart as an ArrayList that can hold Item objects
Object cart[] = new Object[6];
Item item;
String itemName;
double itemPrice;
int quantity;
double totalPrice;
cart.add(item);
cart.add(itemName);
cart.add(itemPrice);
cart.add(quantity);
cart.add(totalPrice);
System.out.println("Welcome to Shopper's Paradise");
System.out.println();
Scanner scan = new Scanner(System.in);
String keepShopping = "y";
do {
System.out.print("Enter the name of the item: ");
itemName = scan.nextLine();
System.out.print("Enter the unit price: ");
itemPrice = scan.nextDouble();
System.out.print("Enter the quantity: ");
quantity = scan.nextInt();
// *** create a new item and add it to the cart
Object newItem ="Hammer";
cart[6] = "Hammer";
totalPrice = 0;
System.out.println("\nCurrent Cart");
// *** print the contents of the cart object
// *** print the total price of the cart
System.out.println(totalPrice += item.getQuantity() * item.getPrice());
System.out.println();
System.out.print("Continue shopping (y/n)? ");
scan.nextLine();
keepShopping = scan.nextLine();
} while (keepShopping.equals("y"));
}//end of main method
}//end of Shop class
-
I'm afraid without seeing the Item class, I can't see what's wrong with your printout. You make the calls to the methods that add, and you attempt to print out the number of items... so we'll need to see your Item class. Please make an attempt at writing the printing code. From there, we can critique and/or correct you. Help yourself before we help you.
Welcome to the Java Forums!
Please have a look at the FAQ before you post again. And, please make use of the [ code] [ /code] tags when posting code- and to see if you used the tags correctly, use the "preview" option when posting.
See you around!