I messed up trying to print out this array list what am I doing wrong I've tried multiple times but when ever it prints it outputs null.
import java.util.ArrayList;
import java.util.Arrays;
import java.text.NumberFormat;
import java.util.Scanner;
//Class header
public class ShoppingCart {
// Start of main method
public static <Item> void main(String[] args) {
// Declare and instantiate a variable that is an ArrayList that can hold
// Product objects
ArrayList<Product> item = new ArrayList<Product>();
// Declare necessary local variables here
String Name = null;
double Price = 0;
int Quantity = 0;
String Seller = null;
Scanner scan = new Scanner(System.in);
String Shop = "yes";
// Write a print statement that welcome's the customer to our shop
/**
*
* create a do while that will be keep looping as long as user wants to
* continue shopping
*/
Product im = new Product(Name, Price, Quantity, Seller);
// do while loop start
do {
// Ask user to enter product name and store it in appropriate local
// variable
System.out.print("Please Enter the Product Name: ");
Name = scan.next();
// Ask user to enter product price and store it in appropriate local
// variable
System.out.print("Please Enter the Price of the Product: ");
Price = scan.nextDouble();
// Ask user to enter quantity and store it in appropriate local
// variable
System.out.print("Please enter the Quantity: ");
Quantity = scan.nextInt();
// Ask user to enter product manufacturer name and store it in
// appropriate local variable
System.out.print("Please Enter the Manufacturer: ");
Seller = scan.next();
System.out.print("Would you like to continue shopping?");
Shop = scan.next();
// create a new Product object using above inputed values
Product item2 = new Product(Name, Price, Quantity, Seller);
// add above created Product to the ArrayList cart if Product has
// available stock
// if stock not available inform user requested product is out of
// stock
// Ask user whether wants to continue shopping
// set the do while loop to continue to loop if Yes option is
// selected
} while (Shop.equals("Yes"));
System.out.println("Product Unit Price Quantity SubTotal");
System.out.println(Name + " " + (Price) + " " + Quantity + " " + (Price * Quantity));
System.out.println("00"); System.out.println(item);
// do while loop end
// header for shopping cart contents
// print details of each product added to the ArrayList
// calculate total price of the shopping cart
// print the total price of the shopping cart
}// end of main method
}// end of Shop class
First of all, why are you doing this
public static <Item> void main(String[] args) {
SHould be
public static void main(String[] args) {
To print the ArrayLIst just do this
System.out.println("Name\tPrice\tQuantity\tSeller\tTotal")
for (Product p : item){
double total = p.price * p.quantity;
System.out.println(p.name + "\t" + p.price + "\t" p.quantity + "\t" + p.seller + "\t" + total);
}
But first you need to add something to the list
Product item2 = new Product(Name, Price, Quantity, Seller);
item.add(item2);
Or even a cleaner looking idea would be override the toString method in the Product class
public class Product {
String name;
String Seller;
double price;
int quantity;
public Product(String name, double price, int quantity, String seller){
this.name = name;
this.seller = seller;
this.price = price;
this.seller = seller;
}
public String toString(){
double total = p.price * p.quantity;
return name + "\t" + price + "\t" quantity + "\t" + seller + "\t" + total;
}
}
To print from list just do this.
for (Product p : item){
System.out.println(p);
}
its because you never add the item2 to the arraylist item
just add
item.add(item2)
There are quite a few errors in your program.
First off, the reason nothing is being printed when you try printing your arraylist is because you never add any element to your array list, to do so you must use the following method.
arrayListName.add(elementToAdd);
Secondly your main method is incorrect, instead of
public static <Item> void main(String[] args) {
it should be
public static void main (String[] args) {
Related
To begin my question, here is my question prompt:
Create a program using classes that does the following in the zyLabs developer below. For this lab, you will be working with two different class files. To switch files, look for where it says "Current File" at the top of the developer window. Click the current file name, then select the file you need.
(1) Create two files to submit:
ItemToPurchase.java - Class definition
ShoppingCartPrinter.java - Contains main() method
Build the ItemToPurchase class with the following specifications:
Private fields
String itemName - Initialized in default constructor to "none"
int itemPrice - Initialized in default constructor to 0
int itemQuantity - Initialized in default constructor to 0
Default constructor
Public member methods (mutators & accessors)
setName() & getName() (2 pts)
setPrice() & getPrice() (2 pts)
setQuantity() & getQuantity() (2 pts)
(2) In main(), prompt the user for two items and create two objects of the ItemToPurchase class. Before prompting for the second item, call scnr.nextLine(); to allow the user to input a new string. (2 pts)
Ex:
Item 1
Enter the item name: Chocolate Chips
Enter the item price: 3
Enter the item quantity: 1
Item 2
Enter the item name: Bottled Water
Enter the item price: 1
Enter the item quantity: 10
(3) Add the costs of the two items together and output the total cost. (2 pts)
Ex:
TOTAL COST
Chocolate Chips 1 # $3 = $3
Bottled Water 10 # $1 = $10
Total: $13
My code:
ItemToPurhase.java
public class ItemToPurchase {
//Private fields - itemName, itemPrice, and itemQuanity
private String itemName = "none";
private int itemPrice = 0;
private int itemQuantity = 0;
/*Default Constructor
itemName - Initialized to "none"
itemPrice - Initialized to 0
itemQuantity - Initialized ito 0
*/
public ItemToPurchase () {
this.itemName = "none";
this.itemPrice = 0;
this.itemQuantity = 0;
}
//public member methods (mutators & accessors)
//setName() & getName()
public void setName (String itemName) {
this.itemName = itemName;
}
public String getName() {
return itemName;
}
//setPrice() & getPrice()
public void setPrice (int itemPrice) {
this.itemPrice = itemPrice;
}
public int getPrice(){
return itemPrice;
}
//setQuantity() & getQuantity()
public void setQuantity (int itemQuantity) {
this.itemQuantity = itemQuantity;
}
public int getQuantity() {
return itemQuantity;
}
//print item to purchase
public void printItemPurchase() {
System.out.println(itemQuantity + " " + itemName + " $" + itemPrice +
" = $" + (itemPrice * itemQuantity));
}
}
ShoppingCartPrinter.java
import java.util.Scanner;
public class ShoppingCartPrinter {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int i = 0;
String productName;
int productPrice = 0;
int productQuantity = 0;
int cartTotal = 0;
ItemToPurchase item1 = new ItemToPurchase();
ItemToPurchase item2 = new ItemToPurchase();
// Get item 1 details from user, create itemToPurchase object
System.out.println("Item 1");
System.out.println("Enter the item name: ");
productName = scnr.next();
item1.setName(productName);
System.out.println("Enter the item price: ");
productPrice = scnr.nextInt();
item1.setPrice(productPrice);
System.out.println("Enter the item quantity: ");
productQuantity = scnr.nextInt();
item1.setQuantity(productQuantity);
System.out.println("");
// Get item 2 details from user, create itemToPurchase object
System.out.println("Item 2");
System.out.println("Enter the item name: ");
productName = scnr.next();
item2.setName(productName);
System.out.println("Enter the item price: ");
productPrice = scnr.nextInt();
item2.setPrice(productPrice);
System.out.println("Enter the item quantity: ");
productQuantity = scnr.nextInt();
item2.setQuantity(productQuantity);
System.out.println("");
// Add costs of two items and print total
cartTotal = (item1.getQuantity() * item1.getPrice()) + (item2.getQuantity() * item2.getPrice());
System.out.println("TOTAL COST");
// cartTotal = item one price + item two price
// Totoal Cost
// item one information
int item1Total = item1.getPrice() * item1.getQuantity();
System.out.println(item1.getName() + " " + item1.getQuantity() + " # $" + item1.getPrice() + " = $" + item1Total);
// item two information
int item2Total = item2.getPrice() * item2.getQuantity();
System.out.println(item2.getName() + " " + item2.getQuantity() + " # $" + item2.getPrice() + " = $" + item2Total);
// Total output
System.out.println("");
System.out.print("Total: $" + cartTotal);
return;
}
}
Although I am getting no errors for most of the submissions, there are 2 submissions that raise the "Exception in thread "main" java.util.InputMismatchException" error.
Example:
Exited with return code 1.
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at ShoppingCartPrinter.main(ShoppingCartPrinter.java:23)
Output differs. See highlights below.
Input:
Chocolate Chips
3
1
Bottled Water
1
10
Your output:
Item 1
Enter the item name:
Enter the item price:
Expected output(!):
Item 1
Enter the item name:
Enter the item price:
Enter the item quantity:
Item 2
Enter the item name:
Enter the item price:
Enter the item quantity:
TOTAL COST
Chocolate Chips 1 # $3 = $3
Bottled Water 10 # $1 = $10
Total: $13
My code seems correct for other inputs that are very similar but for some reason, the compiler that my professor uses keeps prompting this error for a very few cases.
If you have not already done so, I suggest that you read the documentation for class java.util.Scanner.
This line of your code is throwing the InputMismatchException.
productPrice = scnr.nextInt();
That means that scnr read a token that was not an int. This is because your product contained two words, namely Chocolate Chips. So this line of your code only read Chocolate
productName = scnr.next();
and hence method nextInt read Chips which is not an int.
You need to change the code and call method nextLine rather than method next. Again, refer to the documentation to understand why.
Also, after calling method nextInt and before calling method nextLine, you need an extra call to method nextLine. Refer to Scanner is skipping nextLine() after using next() or nextFoo()? to understand why.
Only class ShoppingCartPrinter needs to be changed. Here is the changed code. I have added comments to indicate the changes, namely CHANGE HERE and ADDED THIS LINE.
import java.util.Scanner;
public class ShoppingCartPrinter {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int i = 0;
String productName;
int productPrice = 0;
int productQuantity = 0;
int cartTotal = 0;
ItemToPurchase item1 = new ItemToPurchase();
ItemToPurchase item2 = new ItemToPurchase();
// Get item 1 details from user, create itemToPurchase object
System.out.println("Item 1");
System.out.println("Enter the item name: ");
productName = scnr.nextLine(); // CHANGE HERE
item1.setName(productName);
System.out.println("Enter the item price: ");
productPrice = scnr.nextInt();
item1.setPrice(productPrice);
System.out.println("Enter the item quantity: ");
productQuantity = scnr.nextInt();
item1.setQuantity(productQuantity);
scnr.nextLine(); // ADDED THIS LINE
System.out.println("");
// Get item 2 details from user, create itemToPurchase object
System.out.println("Item 2");
System.out.println("Enter the item name: ");
productName = scnr.nextLine(); // CHANGE HERE
item2.setName(productName);
System.out.println("Enter the item price: ");
productPrice = scnr.nextInt();
item2.setPrice(productPrice);
System.out.println("Enter the item quantity: ");
productQuantity = scnr.nextInt();
item2.setQuantity(productQuantity);
System.out.println("");
// Add costs of two items and print total
cartTotal = (item1.getQuantity() * item1.getPrice())
+ (item2.getQuantity() * item2.getPrice());
System.out.println("TOTAL COST");
// cartTotal = item one price + item two price
// Totoal Cost
// item one information
int item1Total = item1.getPrice() * item1.getQuantity();
System.out.println(item1.getName() + " " + item1.getQuantity() + " # $" + item1.getPrice()
+ " = $" + item1Total);
// item two information
int item2Total = item2.getPrice() * item2.getQuantity();
System.out.println(item2.getName() + " " + item2.getQuantity() + " # $" + item2.getPrice()
+ " = $" + item2Total);
// Total output
System.out.println("");
System.out.print("Total: $" + cartTotal);
return;
}
}
My program is about the user choosing a movie or as many has want to watch from the 7 movies listed and also the price it cost shown. The program will give the user 7 movies to chose from and if they want to chose another the price will add up to the total. So far i have is a array of movies and the price but Im not sure how i should make a user choice for the movies and add the total price. Should i use a switch statement or a loop I'm confused. This is what I have so far:
import java.util.Scanner;
public class MovieHits {
public static void main(String[] args)
{
//Declare Variables
Scanner keyboard = new Scanner(System.in);
int userChoice = 0;
String [] Movie = new String [7];
int [] movieCost ={ 5, 4, 3, 6, 4, 4, 3};
Movie [0] = "Iron Man";
Movie [1] = "Transformers";
Movie [2] = "Godzilla";
Movie [3] = "Fast and Furious";
Movie [4] = "Captain America";
Movie [5] = "X Men";
Movie [6] = "Rio";
//Welcome the user
System.out.println("Hello, Welcome to TC Movies OnDemand.");
//Display the listed movies so the user can know with movie they want to watch
System.out.println("\nChoose which movie you want to watch: ");
for ( int index = 0; index < 7; index = index + 1 )
{
System.out.println(Movie[index]);
System.out.println("\t" + "Price: $" + movieCost[index]);
}
//Switch Statement to give user a menu to choose a movie
switch (userChoice)
{
case 1:
System.out.println("The movie you have chosen.");
break;
You should use loop for printing out the movie selection. After reading the user input you can use switch case to determine which movie was selected.
Your example code doesn't actually read user input, the instantiated Scanner object is never used. Before switch-case, you should have e.g.
userChoice = keyboard.nextInt();
However, there is a more object oriented "Java way" to do this using Map instead of String arrays, and without switch-case:
public class MovieHits {
public static class Movie {
private int cost;
private String name;
public Movie(String name, int cost) {
this.cost = cost;
this.name = name;
}
public int getCost() {
return cost;
}
public String getName() {
return name;
}
}
public static void main(String[] args) {
//Declare Variables
Scanner keyboard = new Scanner(System.in);
int userChoice;
Map<Integer, Movie> movies = new HashMap<Integer, Movie>();
movies.put(1, new Movie("Iron Man", 5));
movies.put(2, new Movie("Transformers", 4));
movies.put(3, new Movie("Godzilla", 3));
// ...
//Welcome the user
System.out.println("Hello, Welcome to TC Movies OnDemand.");
//Display the listed movies so the user can know with movie they want to watch
System.out.println("\nChoose which movie you want to watch: ");
Set<Integer> keys = movies.keySet();
for (Integer key : keys) {
Movie movie = movies.get(key);
System.out.println(key + ": " + movie.getName());
System.out.println("\t" + "Price: $" + movie.getCost());
}
userChoice = keyboard.nextInt();
System.out.println("You have chosen " + movies.get(userChoice).getName());
Inner classes are usually against best practice, but in this case I used it to keep it simple.
If user can select multiple movies, then read userChoice inside a while-loop and break it with a certain number or if user inputs empty line. Inside the loop store the selected movies e.g. in a List, calculate total price for user to see inside the loop, or after all wanted movies are selected.
I am working on an assignment and I have run into a few problems. Here is the Assignment Question and what I've done so far and my question.
Complete ShoppingCart.java as follows:
Declare and instantiate a variable cart to be an empty ArrayList that can hold Product objects. Remember to import ArrayList. Comments in the code indicate where these statements should go.
Fill in the required statements to write a loop that requests required information from the user regards to a product item, create a Product object using inputted information, and add the product to the ArrayList. Ensure user can enter information for multiple products by enabling loop to continue work based on whether user wants to continue shopping. Comments in the code indicate where these statements go.
Print the shopping cart contents by printing each product items stored in the ArrayList. Remember that Product object has toString method. Print the total price of the cart after printing shopping cart contents. Remember to format the output of total price, so that it prints in current format. Comments in the code indicate where these statements go.
Compile and run your program with following inputs (Provide output of your program)
First product as Bicycle Horn with unit price as 7.19, quantity as 2, and manufacturer as Klout.
Second product as Forerunner Watch with unit price as 140.89, quantity as 2, and manufacturer as Garmin.
Here is the code I've written:
//***************************************************************
//ShoppingCart.java
//
//Uses the Product class to create items and add them to a shopping
//cart stored in an ArrayList.
//***************************************************************
// import statements
import java.util.ArrayList;
import java.text.NumberFormat;
import java.util.Scanner;
//Class header
public class ShoppingCart {
//Start of main method
public static <Item> void main(String[] args){
//Declare and instantiate a variable that is an ArrayList that can hold Product objects
ArrayList<Product> item = new ArrayList<Product>();
//Declare necessary local variables here
String Name = null;
double Price = 0;
int Quantity = 0;
String Seller = null;
Scanner scan = new Scanner(System.in);
// Write a print statement that welcome's the customer to our shop
/**
* create a do while that will be keep looping as long as user wants to continue shopping
*/
String keepShopping = "Yes";
Product item1 = new Product(Name, Price, Quantity, Seller);
//do while loop start
do
{
//Ask user to enter product name and store it in appropriate local variable
System.out.print("Please Enter the Product Name: ");
Name = scan.next();
//Ask user to enter product price and store it in appropriate local variable
System.out.print("Please Enter the Price of the Product: ");
Price = scan.nextDouble();
//Ask user to enter quantity and store it in appropriate local variable
System.out.print("Please enter the Quantity: ");
Quantity = scan.nextInt();
//Ask user to enter product manufacturer name and store it in appropriate local variable
System.out.print("Please Enter the Manufacturer: ");
Seller = scan.next();
// create a new Product object using above inputed values
Product newitem = new Product(Name, Price, Quantity, Seller);
//add above created Product to the ArrayList cart if Product has available stock
// if stock not available inform user requested product is out of stock
//Ask user whether wants to continue shopping
//set the do while loop to continue to loop if Yes option is selected
} while (keepShopping.equals("Yes"));
// do while loop end
// header for shopping cart contents
// print details of each product added to the ArrayList
// calculate total price of the shopping cart
// print the total price of the shopping cart
}//end of main method
}//end of Shop class
And the Product class the professor provided:
//***************************************************************
//Product.java
//Represents an item in a shopping cart.
//***************************************************************
import java.text.NumberFormat;
public class Product
{
private String name;
private double price;
private int quantity;
private double subtotal;
private String manufacturer;
private int inventory;
// -------------------------------------------------------
// Create a new item with the given attributes.
// -------------------------------------------------------
public Product (String name, double price, int quantity, String manufacturer)
{
this.name = name;
this.price = price;
this.quantity = quantity;
this.manufacturer = manufacturer;
subtotal = price*quantity;
inventory = 10;
}
public Product(String itemName, double itemPrice, int quantity2) {
// TODO Auto-generated constructor stub
}
// -------------------------------------------------------
// Return a string with the information about the Product
// -------------------------------------------------------
public String toString ()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return (manufacturer + " " + name + "\t\t " + fmt.format(price) + "\t " + quantity
+ "\t\t" + fmt.format(subtotal));
}
// Returns the unit price of the Product
public double getPrice()
{
return price;
}
// Returns the name of the Product
public String getName()
{
return name;
}
// Returns the quantity of the Product
public int getQuantity()
{
return quantity;
}
// Returns the sub total of the Product
public double getSubTotal()
{
return subtotal;
}
// Returns product manufacturer
public String getManufacturer()
{
return manufacturer;
}
// Checks whether product is in stock
// if after inventory get below stock after processing order, then
// places order to replenish stock
public boolean checkInventory()
{
boolean flag = false;
if (inventory > quantity)
{
flag = true;
inventory = inventory - quantity;
if (inventory <= 0)
placeOrder(quantity);
}
return flag;
}
// Replenishes stock to 10 times the quantity of last order
private void placeOrder(int orderQuantity)
{
inventory = orderQuantity * 10;
}
}//end of class Item
I would write a comment but for some reason its not giving me the option.
I don't understand the question? Do you just want me to do the assignment? What don't you understand?
It doesn't look like you're ever adding anything to the arrayList that you made. You created the product object but you need to add it to the list.....
Also it looks like you created a second constructor in your product class that I don't think you are using.
I am a java beginner and I am coding a program that gets the name of the item, units of that item, price/unit and the total price. I am trying to put those values in different arrays
so I can access them later when I create a sort of a receipt but I don't know how to assign those values in array positions and then access those same positions without having to hard-code. A loop is the best option but I dont know how to set this thing up. Help and suggestions would really be appreciated. Keep in mind that I cant do advanced stuff like matrices and 3D arrays. If you can keep it simple it would be awesome.
This is the main class, I have a tester class with main() that runs userInput() and menu() but theres no point in putting that in because its only 2 lines of code.
import java.util.Scanner;
public class GroceryList {
// instance variables
Scanner Price, Items, NumItems, Units;
private double myGross, myNet;
private final double STATETAX;
private double totalPrice, unitPrice;
private String itemName;
private int totalUnits;
///////////////////////////////////////////// arrays I will use
private double[] totalPrice1;
private double[] unitPrice1;
private String[] itemName1;
private int[] totalUnits1;
public GroceryList()
{
STATETAX = 0.06;
double[] totalPrice = new double[50];
double[] unitPrice = new double[50];
String[] itemName = new String[50];
int[] totalUnits = new int[50];
}
public void userInput()
{
Scanner Price = new Scanner(System.in);
Scanner Items = new Scanner(System.in);
Scanner Units = new Scanner(System.in);
Scanner NumItems = new Scanner(System.in);
int u, c, totalItems;// c is the number of items that has to equal totalItems in order for the loop to break
double price;
String item;//gets the name of the item
c=0;
System.out.println("Welcome to Grocery List ! \n");
System.out.print("Enter the total number of items you want to buy (not total units !) : ");
totalItems = NumItems.nextInt();
System.out.println();
do
{
c++ ;
System.out.print("Enter the item name : ");
item = Items.nextLine();
System.out.print("Enter the units of " + item + " you want to buy : ");
u = Units.nextInt();
System.out.print("Enter the price of a/n " + item + " : $");
price = Price. nextDouble();
/*this would make only one value appear at the receipt, which would be only one item name, one unit price, one price/unit, one total price and the other values calculated
would not appear on the receipt because you cant assign more than 1 value to a variable so thats why I need arrays.
*/
itemName = item;
totalUnits = u;
unitPrice = price;
calc(u,price,item);
}
while (c < totalItems);
}
public void calc(int u, double p, String i)
{
double total;//total amount of $ for 1 item
total = u*p;
System.out.println("Total price of " + i + " : $" + total + "\n");
grossPay(total);
totalPrice = total;
}
public void grossPay(double total)
{
double gross;
myGross += total;
}
public double tax()
{
double temp;
temp = myGross*STATETAX;
myNet = myGross - temp;
return myNet;
}
public void menu()
{
System.out.printf("%-10s %6s %11s %11s" , "ITEM :" , "UNITS :" , "PRICE :" , "TOTAL :");
System.out.println();
System.out.printf("%-11s %2d %7s $%4.2f %5s $%2.2f", itemName, totalUnits,"", unitPrice,"", totalPrice);
System.out.println();
}
public void payment()
{
System.out.println("Amount before tax : $" + myGross);
System.out.println("Amount after tax : $" + tax());
}
}//end GroceryList
Let's start with a little restructure ;)
First of all, you really don't need the array totalPrice1, the total price is the total price, there's only one...(IMHO)
Instead of initialising the arrays in the constructor, you should initialise them in the userInput method, this is when you know how many items the user will want to enter. Otherwise you will run into problems if I want to enter 51 items ;)
System.out.println("Welcome to Grocery List ! \n");
System.out.print("Enter the total number of items you want to buy (not total units !) : ");
totalItems = NumItems.nextInt();
System.out.println();
unitPrice1 = new double[totalItems];
itemName1 = new String[totalItems];
totalUnits1 = new int[totalItems];
(nb- You have bug in your original code, in the constructor, you had declared the arrays as local variables, but used the wrong names any way, this would leave the instance fields uninitialised, raising a NullPointerException)
While it's certainly not an error, it would simpler to increment c at the end of the loop...
do {
//...
calc(u, price, item);
c++;
} while (c < totalItems);
This will mean you don't need to constantly keep adjusting the position for the arrays.
In you "collection" loop, you need to assign the values the user has entered to each array...
do {
//...
itemName1[c] = item;
totalUnits1[c] = u;
unitPrice1[c] = price;
//...
} while (c < totalItems);
Having said all that, it would actually be easier to use something like a for-next loop...
for (int c = 0; c < totalItems; c++) {
//...
}
IMHO...
Finally, when you're ready, you can print the receipt by simply looping through the arrays...
for (int index = 0; index < totalItems; index++) {
double itemCost = unitPrice1[index] * totalUnits1[index];
System.out.println(itemName1[index] + " # " + unitPrice1[index] + " x " + totalUnits1[index] + " = " + cost);
}
System.out.println("Total Cost: " + totalPrice);
Some feedback ;)
Having said all that, I would, personally, create yourself a simple Object which contained all the required information, for example;
public class ShoppingItem {
public String name;
public double unitPrice;
public double quantity;
}
Then, all you would need is a single array, for example...
//private double[] unitPrice1;
//private String[] itemName1;
//private int[] totalUnits1;
private ShopingItem[] items;
Then, as required, you would simply create a new instance of this item and fill it out, for example...
items[c] = new ShoppingItem();
items[c] = item;
items[c] = u;
items[c] = price;
//itemName1[c] = item;
//totalUnits1[c] = u;
//unitPrice1[c] = price;
And printing the receipt would look for like...
for (ShoppingItem item : items) {
double itemCost = item.unitPrice * item.quantity;
System.out.println(item.name + " # " + item.unitPrice + " x " + item.quantity + " = " + cost);
}
System.out.println("Total Cost: " + totalPrice);
For a more "advanced" output, I would encourage you to take a look a something like String#format and/or System.out.printf
Take a look at this example for some ideas ;)
Ideally you would (wrote this as I misread your meaning of sort):
Create an Object Item which has the fields name, totalPrice, unitPrice, totalUnits. Then in your grocery list you don't need to have 4 arrays, just one array of Items. Saves the dubious task of having to keep track of indices.
If you also create an ItemComparator class that implements Comparator you can define how they should be sorted and you can then sort your array using
Collections.sort(Arrays.asList(itemsList), new ItemComparator());
You also don't need four Scanners, you can use the same scanner since they are all on System.in
I am doing a Java Application for a class and need help with errors that are coming up after running the app.
The app is supposed to allow the user to add an item to the shopping cart(item name, price, quantity). The user described item will be added to the shopping cart array, and then it will be printed out once it is successfully added.
The shopping cart has a max capacity of 5 items initially, but if the cart size is > 5, it will be increased + 3, via the increaseSize method.
As stated below, I believe that the addToCart method is not adding the user described item to the cart. That is why it is a null value within the toString method.
So, I basically need help with the addToCart method.
Please correct me if I am wrong. Thank you.
An output from running the app is as follows:
run:
Enter the name of the item: a
Enter the unit price: 2
Enter the quantity: 2
Exception in thread "main" java.lang.NullPointerException
at shop.ShoppingCart.toString(ShoppingCart.java:62)
at java.lang.String.valueOf(String.java:2854)
at java.io.PrintStream.println(PrintStream.java:821)
at shop.Shop.main(Shop.java:49)
Java Result: 1
Below is the ShoppingCart Class.
The toString method should not have any errors being produced, but I believe that the problem lies within the addToCart method.
// **********************************************************************
// ShoppingCart.java
//
// Represents a shopping cart as an array of items
// **********************************************************************
import java.text.NumberFormat;
public class ShoppingCart
{
private Item[] cart;
private int itemCount; // total number of items in the cart
private double totalPrice; // total price of items in the cart
private int capacity; // current cart capacity
// -----------------------------------------------------------
// Creates an empty shopping cart with a capacity of 5 items.
// -----------------------------------------------------------
public ShoppingCart()
{
capacity = 5;
cart = new Item[capacity];
itemCount = 0;
totalPrice = 0.0;
}
// -------------------------------------------------------
// Adds an item to the shopping cart.
// -------------------------------------------------------
public void addToCart(String itemName, double price, int quantity)
{
Item temp = new Item(itemName, price, quantity);
totalPrice += (price * quantity);
itemCount += quantity;
cart[itemCount] = temp;
if(itemCount==capacity)
{
increaseSize();
}
}
// -------------------------------------------------------
// Returns the contents of the cart together with
// summary information.
// -------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String contents = "\nShopping Cart\n";
contents += "\nItem\t\tUnit Price\tQuantity\tTotal\n";
for (int i = 0; i < itemCount; i++)
contents += cart[i].toString() + "\n";
contents += "\nTotal Price: " + fmt.format(totalPrice);
contents += "\n";
return contents;
}
// ---------------------------------------------------------
// Increases the capacity of the shopping cart by 3
// ---------------------------------------------------------
private void increaseSize()
{
Item[] temp = new Item[capacity+3];
for(int i=0; i < capacity; i++)
{
temp[i] = cart[i];
}
cart = temp;
temp = null;
capacity = cart.length;
}
}
Below is the Shop Main.
The ArrayList is not in use at this time, but will be later once the toString errors are corrected.
package shop;
// ***************************************************************
// Shop.java
//
// Uses the Item class to create items and add them to a shopping
// cart stored in an ArrayList.
// ***************************************************************
import java.util.ArrayList;
import java.util.Scanner;
public class Shop
{
public static void main (String[] args)
{
ArrayList<Item> cart = new ArrayList<Item>();
Item item;
String itemName;
double itemPrice;
int quantity;
Scanner scan = new Scanner(System.in);
String keepShopping = "y";
ShoppingCart cart1 = new ShoppingCart();
do
{
System.out.print ("Enter the name of the item: ");
itemName = scan.next();
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
cart1.addToCart(itemName, itemPrice, quantity);
// *** print the contents of the cart object using println
System.out.println(cart1);
System.out.print ("Continue shopping (y/n)? ");
keepShopping = scan.next();
}
while (keepShopping.equals("y"));
}
}
Below is the Item Class:
package shop;
// ***************************************************************
// Item.java
//
// Represents an item in a shopping cart.
// ***************************************************************
import java.text.NumberFormat;
public class Item
{
private String name;
private double price;
private int quantity;
// -------------------------------------------------------
// Create a new item with the given attributes.
// -------------------------------------------------------
public Item (String itemName, double itemPrice, int numPurchased)
{
name = itemName;
price = itemPrice;
quantity = numPurchased;
}
// -------------------------------------------------------
// Return a string with the information about the item
// -------------------------------------------------------
public String toString ()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return (name + "\t" + fmt.format(price) + "\t" + quantity + "\t"
+ fmt.format(price*quantity));
}
// -------------------------------------------------
// Returns the unit price of the item
// -------------------------------------------------
public double getPrice()
{
return price;
}
// -------------------------------------------------
// Returns the name of the item
// -------------------------------------------------
public String getName()
{
return name;
}
// -------------------------------------------------
// Returns the quantity of the item
// -------------------------------------------------
public int getQuantity()
{
return quantity;
}
}
I believe the problem is caused by these two lines from addToCart():
itemCount += quantity;
cart[itemCount] = temp;
Unless quantity is 0, this means cart[0] will never contain anything. In fact, whatever the value of quantity, you will be leaving that many gaps in cart (e.g. if quantity is 2, cart[0] and cart[1] will be null).
Since an Item already includes the quantity, I believe you meant to do this:
cart[itemCount] = temp;
itemCount += 1;
This way the first item will be put in cart[0], the second in cart[1], and so on.
Another small piece of advice: if you are concatenating any object with a String, you don't need to call toString() on the object. Java will automatically call String.valueOf() on the object, which avoids a NullPointerException because it returns the String "null" instead. In this case, it might have helped you debug the problem because you would have noticed the null String appearing in your output. You would have to change your code to the following:
for (int i = 0; i < itemCount; i++)
contents += cart[i] + "\n";
public void addToCart(String itemName, double price, int quantity)
{
Item temp = new Item(itemName, price, quantity);
totalPrice += (price * quantity);
itemCount += quantity;
cart[itemCount] = temp;
if(itemCount==capacity)
{
increaseSize();
}
}
This code is broken. You try to add to cart at index itemCount. This will throw index out of bound execptions. basicly you increase the size of your cart to late.
This also causes a lot off empty places in your array. You do not add your next Item at the next place of your arra but you jump quantity places ahead. This causes some of the values in your array to be null. This is most likly causing the NullPointerExceütion in toString().
For how to implement this self growing list. You might want to take a look at the class ArrayList that comes with the JDK.
there are some other points i want to point out:
google javaDoc and use it instead of your own custom comments
replace your for-loop in toString() with a for-each-loop
The problem lies both in your addToCart method.
If you type this code:
ShoppingCart shopcart= new ShoppingCart();
shopcart.addToCart("foo", 3, 2);
The shopping cart will have the following attributes:
totalPrice=6
itemCount = 2;
cart = { null, null, foo, null, null};
The problem is that addToCart only modify the "itemcount" element of the array cart without considering the number of element added.
Moreover, cart[0] will stay at null forever.
You should remplace theses lines
itemCount += quantity;
cart[itemCount] = temp;
by
for ( int i =0 ; i<quantity;i++)
{
cart[itemCount+i] = temp;
}
itemCount += quantity;