0

I have an array list with the name and cost of an item, however, I'd like to separate the two, especially so that I can sum the values of the costs.

heres what I have so far:

import java.util.ArrayList;

public class henrys {

    public static ArrayList<String> products = new ArrayList<String>();

    public static void main(String[] args) {
        products.add("Calvin Klein Blue Shorts, Size: Medium, $45");
        products.add("Ralph Lauren Blue Shirt, Size: Large, $50");
        products.add("Gap Beige Khakis, Size: 30, $20");
        products.add("Calvin Klein Black Shirt, Size: Medium, $35");
        products.add("USA Jersey White, Size: Medium, $100");
        System.out.println((products)); 
    }
}
Joseph Boyle
  • 560
  • 5
  • 15

1 Answers1

3

Creating an ArrayList like this really doesn't make sense, and goes completely against the purpose of a language centered around objects.

Create a Product class, give it a name, price, and size field, and then create an ArrayList of Product objects.

To get the sum of the prices, you could iterate over every Product in the ArrayList and add its price:

Sidenote: Storing monetary values as a double is horrible idea. I only did it to show you how to get started.

FINAL EDIT

You need to create a class called Product with the following code:

public class Product {

    public String name, size;
    public double price;

    public Product(String name, String size, double price){
        this.name = name;
        this.size = size;
        this.price = price;
    }

}

In your Main Class:

public static void main(String[] args){
    ArrayList<Product> products = new ArrayList<Product>();
    products.add(new Product("Shorts", "Small", 5.45);
    products.add(new Product("Shirt", "Large", 15.15);
    products.add(new Product("Hat", "Small", 10.25);

    //Calculate total price.
    double price = 0.00;
    for(Product p : products){
        price += p.price;
    }
    System.out.println("Total cost: " + price);

}
Joseph Boyle
  • 560
  • 5
  • 15