0

I have an ArrayList that contains objects. Each of the object has 3 values: String name, double price, int quantity. How to write method that will sum all doubles of objects and print the result. And also if int quantity>1, price will be multiplied by quantity.

Code that i wrote so far:

Product class

public class Product {

private String name;
private double price;
private int quantity;

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

public String getName() {
    return name;
}

public double getPrice() {
    return price;
}

public static Product createProduct(String name, double price, int quantity){
    return new Product(name, price, quantity);
}  
}

Product list class

import java.util.ArrayList;
import java.util.List;

public class ProductList {

private String name;

List<Product> newList;

public ProductList(String name) {
    this.name = name;
    this.newList = new ArrayList<>();
}

public boolean addNewProduct(Product product) {
    if (findProduct(product.getName()) >= 0) {
        System.out.println("Product is already on the list");
        return false;
    }
    newList.add(product);
    return true;
}

public boolean removeProduct(Product product) {
    if (findProduct(product.getName().toUpperCase()) < 0) {
        System.out.println("Product not found");
        return false;
    }
    newList.remove(product);
    return true;
}

private int findProduct(String productName) {
    for (int i = 0; i < newList.size(); i++) {
        Product product = newList.get(i);
        if (product.getName().equals(productName)) {
            return i;
        }
    }
    return -1;
}

public Product queryProduct(String name) {
    int position = findProduct(name);
    if (position >= 0) {
        return this.newList.get(position);
    }
    return null;
}

public double sumProducts() {
    double sum = 0;
    for (int i = 0; i < newList.size(); i++) {
        sum += newList.get(i).getPrice();
    }
    return sum;
}

/*public boolean listProducts(){};

public boolean updateProduct(){};
*/

}

Simulation class:

public class Simulation {

private static Scanner scanner = new Scanner(System.in);
private static ProductList myProductList = new ProductList("My list");

private static void addNewProduct() {
    System.out.println("Enter new product name: ");
    String name = scanner.nextLine();
    System.out.println("Enter new product price: ");
    double price = scanner.nextDouble();
    System.out.println("Enter new product quantity");
    int quantity = scanner.nextInt();
    Product newProduct = Product.createProduct(name, price, quantity);
    if (myProductList.addNewProduct(newProduct) == true) {
        System.out.println("New product added: " + name + " | price: " + price + " | quantity: " + quantity);
    }
}

private static void removeProduct() {
    System.out.println("Enter product name: ");
    String name = scanner.nextLine().toUpperCase();
    Product existingProduct = myProductList.queryProduct(name);
    if (existingProduct == null) {
        System.out.println("No such product");
        return;
    }
    if (myProductList.removeProduct(existingProduct)) {
        System.out.println("Sucessfully deleted product: " + existingProduct.getName());
    } else {
        System.out.println("Error deleting");
    }

}

private static void printActions() {
    System.out.println("Avaiable actions");
    System.out.println("press: ");
    System.out.println("0 - to shut down\n" +
            "1 - to add new product\n" +
            "2 - to remove product\n" +
            "3 - to sum all products");
}

private static void sumProducts(){
    myProductList.sumProducts();
}


public static void main(String[] args) {

    printActions();

    boolean quit = false;
    while (!quit)
        try {
            System.out.println("\nEnter action: ");
            int action = scanner.nextInt();
            scanner.nextLine();
            switch ((action)) {
                case 0:
                    System.out.println("\nShutting down...");
                    quit = true;
                    break;
                case 1:
                    addNewProduct();
                    break;
                case 2:
                    removeProduct();
                    break;

            }

        } catch (InputMismatchException e) {
            System.out.println("Bad key pressed, only values form 0 to 2 accepted");
            scanner.nextLine();
        }

}

}

Thanks in advance

5
  • 2
    This looks more like a code writing request and less a specific appropriate question. Where's your attempt? What's wrong with your attempt? Commented May 9, 2017 at 1:16
  • products.stream().mapToDouble(p -> p.getPrice() * p.getQuantity()).sum() Commented May 9, 2017 at 1:23
  • You've already written the method to sum them in sumProducts() so is your question just how to print out the sum? The quantity is always 0 and you sometimes call findProduct() with the regular name, and sometimes the uppercase name. Also, you don't need to use a C-style for-loop to loop over a list of objects; you can use an enhanced for-loop. Commented May 9, 2017 at 1:26
  • You do realise that double is not an appropriate data type for a sum of money, if you want exact calculations, right? You can't add and multiply double values and expect them to behave like decimals. The BigDecimal class would suit you better. Commented May 9, 2017 at 1:37
  • Thanks everyone for answers, I'll try to figure that out. Commented May 9, 2017 at 1:49

3 Answers 3

1

You can do it in one line using Java 8.

public double sumProducts() { 
    return newList.stream().mapToDouble(product -> product.getPrice() * product.getQuantity()).sum();
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you use double to store the price, you will get incorrect answers when you try to add and multiply the values. For example, 0.1 + 0.2 is NOT the same double as 0.3. If you want accurate arithmetic for decimal numbers, you should use the BigDecimal class in place of double. If you don't do that, I can guarantee that your program will sometimes give wrong answers.

So you need to change your Product class as follows.

public class Product {

    private String name;
    private BigDecimal price;
    private int quantity;

    public Product(String name, BigDecimal price, int quantity) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public static Product createProduct(String name, BigDecimal price, int quantity){
        return new Product(name, price, quantity);
    }  
}

You will also need to make corresponding changes in the code that calls the methods of this class.

Once you've done that, you can use the methods of the BigDecimal class to do arithmetic. It might look something like this.

public BigDecimal calculateTotalPrice() {
    BigDecimal total = BigDecimal.ZERO;
    for (Product product : newList) {
        BigDecimal linePrice = product.getPrice().multiply(new BigDecimal(product.getQuantity()));
        total = total.add(linePrice);
    }
    return total;
}

1 Comment

Thanks for advice and sharing your knowledge. I'll definitely make changes you've suggested.
0

the sum of each product was missing multiply by its quantity.

public double sumProducts() {
    double sum = 0;
    for (int i = 0; i < newList.size(); i++) {
        Product product = newList.get(i);
        sum += product.getPrice() * product.getQuantity();
    }
    return sum;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.