8 Replies - 24161 Views - Last Post: 07 April 2012 - 05:22 AM Rate Topic: -----

#1 perryftw  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 06-April 12

ArrayList Sum, find sum of shopping list

Posted 06 April 2012 - 12:23 PM

SO the objective of the program is to build a shopping list and then display it to the user. However, I'm having a "method getPrice in class Item cannot be applied to given types" error and I can't figure out why. Here's the code:

// ***************************************************************
//   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;
    }
}

// ***************************************************************
// 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;
import java.text.NumberFormat;
public class Shop
{
   public static void main (String[] args)
   {
  //*** declare and instantiate a variable cart to be an empty ArrayList
	ArrayList<Item> Cart = new ArrayList<Item>();

   Item item;
      String itemName;
      double itemPrice;
      int quantity;
   double totalPrice = 0.0;
      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
   		item = new Item (itemName, itemPrice, quantity);
			Cart.add(item);
			
			
         // *** print the contents of the cart object using println
			for (int i = 0; i < Cart.size(); i++)
			{
				System.out.println(Cart.get(i));
				totalPrice = Item.getPrice(i) * Item.getQuantity(i);

			}
			

			NumberFormat fmt = NumberFormat.getCurrencyInstance();
			
			System.out.println("The total price is: " + fmt.format(totalPrice));
				
				
         System.out.print ("Continue shopping (y/n)? ");
      scan.nextLine();
         keepShopping = scan.nextLine();
      }while (keepShopping.equals("y"));
   }
}



I'm trying to find a way to calculate and print the total price of the entire arrayList at the end of the for loop. Any suggestions?

Is This A Good Question/Topic? 0
  • +

Replies To: ArrayList Sum, find sum of shopping list

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8378
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: ArrayList Sum, find sum of shopping list

Posted 06 April 2012 - 12:38 PM

getPrice() does not accept any parameter
it has to be applied to a Item object that you have to extract from your ArrayList

            for (int i = 0; i < Cart.size(); i++)
            {
                Item itm = Cart.get(i);
                System.out.println(itm);
                totalPrice = itm.getPrice() * itm.getQuantity();
            }



Was This Post Helpful? 2
  • +
  • -

#3 karabasf  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 202
  • View blog
  • Posts: 417
  • Joined: 29-August 10

Re: ArrayList Sum, find sum of shopping list

Posted 06 April 2012 - 01:08 PM

// *** print the contents of the cart object using println
for (int i = 0; i < Cart.size(); i++){
	System.out.println(Cart.get(i));
	totalPrice = Item.getPrice(i) * Item.getQuantity(i);
}
   
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println("The total price is: " + fmt.format(totalPrice));



Also, I think this should be moved outside the do-while loop. I suppose you first want to enter all the items which are in the cart, including the properties of that item

After all those are entered, loop for each item in the cart to retrieve those properties. So you'd have something like this (note that I used a for each loop):

for each Item it in cart{
  Print out the name of it
  TotalPrice += it.Quantitiy * it.Price
}

//Print out the results



However, if you don't understand the for each loop, use your for-loop instead. Then:

//Note Cart.size represent the amount of items the cart is holding
for (int i = 0; i < Cart.Size() ; i++){
  //Make a temporary Item object
  Item temp = cart.get(i) //Get the item at position i

  //Print the Item object (you'll manage that)
  //Get the "subprice" (Quantity * Price) and add it to the total price
  totalprice += it.getQuantity() * it.getPrice(); 
}

//Print out the results




Good luck ^^

Edit: rats, didn't see that pbl already posted the correction(s) :)

This post has been edited by karabasf: 06 April 2012 - 01:18 PM

Was This Post Helpful? 1
  • +
  • -

#4 perryftw  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 06-April 12

Re: ArrayList Sum, find sum of shopping list

Posted 06 April 2012 - 08:40 PM

View Postpbl, on 06 April 2012 - 12:38 PM, said:

getPrice() does not accept any parameter
it has to be applied to a Item object that you have to extract from your ArrayList

            for (int i = 0; i < Cart.size(); i++)
            {
                Item itm = Cart.get(i);
                System.out.println(itm);
                totalPrice = itm.getPrice() * itm.getQuantity();
            }




I did try this before and the output for totalPrice is wrong. It definitely compiles but after the first item, the math gets all weird.
Was This Post Helpful? 0
  • +
  • -

#5 perryftw  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 06-April 12

Re: ArrayList Sum, find sum of shopping list

Posted 06 April 2012 - 08:48 PM

View Postperryftw, on 06 April 2012 - 08:40 PM, said:

View Postpbl, on 06 April 2012 - 12:38 PM, said:

getPrice() does not accept any parameter
it has to be applied to a Item object that you have to extract from your ArrayList

            for (int i = 0; i < Cart.size(); i++)
            {
                Item itm = Cart.get(i);
                System.out.println(itm);
                totalPrice = itm.getPrice() * itm.getQuantity();
            }




Also, to specify, I'm trying to get the sum of all the totalPrice's of the ArrayList. I tried
            for (int i = 0; i < Cart.size(); i++)
            {
                Item itm = Cart.get(i);
                System.out.println(itm);
                totalPrice += itm.getPrice() * itm.getQuantity();
            }



I tried this before and the output for totalPrice is wrong. It definitely compiles but after the first item, the math gets all weird.

Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8378
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: ArrayList Sum, find sum of shopping list

Posted 06 April 2012 - 08:57 PM

View Postperryftw, on 06 April 2012 - 11:40 PM, said:

I did try this before and the output for totalPrice is wrong. It definitely compiles but after the first item, the math gets all weird.

So ? What are we supposed to do ?
1) you haven't post you code so we cannot validate it
2) you haven't qualified "weird". What are they suposed to be, and what do you have ?
Was This Post Helpful? 0
  • +
  • -

#7 perryftw  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 06-April 12

Re: ArrayList Sum, find sum of shopping list

Posted 06 April 2012 - 09:10 PM

View Postpbl, on 06 April 2012 - 08:57 PM, said:

View Postperryftw, on 06 April 2012 - 11:40 PM, said:

I did try this before and the output for totalPrice is wrong. It definitely compiles but after the first item, the math gets all weird.

So ? What are we supposed to do ?
1) you haven't post you code so we cannot validate it
2) you haven't qualified "weird". What are they suposed to be, and what do you have ?


Sorry, I was using the same code you posted before, just had the '+=' assignment to totalPrice in an effort to get the total sum of all the "totalPrice" elements of the array. When I did that, the totalPrice would then add the previous totalPrice to twice the new totalPrice of the for loop. I finall figured it out though. I just had to move the for loop that gets the sum outside of the do-while loop.

// ***************************************************************
// 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;
import java.text.NumberFormat;
public class Shop
{
   public static void main (String[] args)
   {
  //*** declare and instantiate a variable cart to be an empty ArrayList
	ArrayList<Item> Cart = new ArrayList<Item>();

   Item item;
      String itemName;
      double itemPrice;
      int quantity;
   double totalPrice = 0.0;
	double sum = 0.0;
      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
   		item = new Item (itemName, itemPrice, quantity);
			Cart.add(item);
			
			
         // *** print the contents of the cart object using println
			for (int i = 0; i < Cart.size(); i++)
			{
				Item itm = Cart.get(i);
				System.out.println(itm);
			}

		//Print out the results
			System.out.print ("Continue shopping (y/n)? ");
      scan.nextLine();
         keepShopping = scan.nextLine();
      }while (keepShopping.equals("y"));
			
			
			for (int i = 0; i < Cart.size() ; i++)
			{
				Item itm = Cart.get(i);
				System.out.println(itm);
				totalPrice = itm.getQuantity() * itm.getPrice();
				sum += totalPrice;
			}
			
			NumberFormat fmt = NumberFormat.getCurrencyInstance();
			
			System.out.println("The total price is: " + fmt.format(sum));

   }
}


Sorry for the confusion! and thanks for all the help!
Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8378
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: ArrayList Sum, find sum of shopping list

Posted 06 April 2012 - 09:33 PM

Works for me

Enter the name of the item: aaa
Enter the unit price: 20,0
Enter the quantity: 5
aaa 20,00 $ 5 100,00 $
Continue shopping (y/n)? y
Enter the name of the item: bbb
Enter the unit price: 10,0
Enter the quantity: 4
aaa 20,00 $ 5 100,00 $
bbb 10,00 $ 4 40,00 $
Continue shopping (y/n)? n
aaa 20,00 $ 5 100,00 $
bbb 10,00 $ 4 40,00 $
The total price is: 140,00 $
Was This Post Helpful? 0
  • +
  • -

#9 codeMonkey_1066  Icon User is offline

  • D.I.C Head

Reputation: 19
  • View blog
  • Posts: 71
  • Joined: 22-March 12

Re: ArrayList Sum, find sum of shopping list

Posted 07 April 2012 - 05:22 AM

A couple of stylistic notes.

If you need to iterate over the contents of a collection your better off using the
for each syntax of the loop

 double sum = 0.0 ;
 for(Item itm : cart )
 {
  System.out.println(itm);  
  double totalPrice = itm.getQuantity() * itm.getPrice();  
  sum += totalPrice;  
 }


---

Using a do/while loop can be inadvisable especially when the contents of the do block are long enough that you have to scroll
down as having the logic of the loop far apart makes it harder to understand.

If possible it's better to just use a while loop if you can, or at least encapsulate as much of the processing in separate methods.

some alternative options are

// do and while in easy sight of each other
do
{
 addNewItem();
 displayCart();
 keepShopping = keepShopping();
}
while(keepShopping.equals("y");



 // while loop using a boolean rather than a string ;
 boolean keepShopping = true;
 while(keepShopping)
 {
  ...
  String response = scanner.readLine();
  keepShopping = response.equals("y");
 }



  // slightly long winded for statement 
  // but All the loop logic is in one place.

 for(boolean keepShopping = true;
     keepShopping ;
     keepShopping = continueShopping()
 )
 {
  addNewItem();
  displayCart();
 }





---
Your code would also be a lot clearer if you split up the processing into to several smaller methods rather than just one large method

 public staitc void main(String ...)
  throws Exception
 {
  List<Item> cart = new ArrayList<Item>();
  Scanner scan = new Scanner(System.in);  

  for(
   booean keepShopping = true; 
   keepShopping ;
   keepShopping = continueShopping(scanner) 
  )
  {
   Item newItem = inputItem(scanner);
   cart.add(newItem);
   displayCart(cart);
  }

  displayBill(cart);

 }




Making your code easier to read makes it easier to write.

Hope you find this advice helpful.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1