javalist

Adding a item to a list


I need to add a class item to a list, it has to be added by keyboard input. I'm not able to add its attributes

Product Class

import java.util.*;

public class Product {
    public double price;
    public int quantity;
    private String id_product;
    
    public Prodotto (double price, int quantity, String id_product) {
        this.price = price;
        this.quantity = quantity;
        this.id_product = id_product;
    }
    public double getPrice() {
        return price;
    }
    public int getQuantity() {
        return quantity;
    }
    
    public String getId_product() {
        return id_product;
    }
    


}

ProductList Class

import java.util.*;

public class ProductList {
    List <Product> productList;
    
    public ProductList() {
        productList = new LinkedList<Product>();
    }
    
    public void addProduct(Product p) {
        productList.add(p);
    }
    
    public int getSize() {
        return productList.size();
    }
    
    public Product getProduct(int i) {
        return productList.get(i);
    }

    public void add(String next) {
        
    }
    
    
}

And the the Main Class, it's still in development with additional operations that i removed to make it more clear for you, but the first it's the one that is giving me trouble

import java.util.*;

public class WarehouseManagement {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    
    ProductList el_product = new ProductList();
    
    Scanner sc = new Scanner(System.in);
    
    boolean stop = false;
    while(!stop) {
        System.out.println("Available Operations:");
        System.out.println("1 - Add Product");
        
        System.out.print("Insert your choice: ");
        int choice = sc.nextInt();
        
        Product [] products
        
        
        switch (choice) {
            case 1:
                System.out.print("Insert product: ");
                el_product.add(sc.next());
                
                break;
        }
    
        
        }
    }

    }


With this i can add a product but not his price, quantity and Id, how can i do that?


Solution

  • What I recommend is that you add a static method to Product to take input through a Scanner and return a Product

    public static Product createProduct (Scanner s) {
        double price, 
        int quantity;
        String id_product;
        System.out.println("Enter the price");
        price = s.nextDouble();
        System.out.println("Enter the quantity");
        quantity = s.nextInt();
        System.out.println("Enter the product ID");    
        id_product = s.next();
        return new Product(price, quantity, id_product);
    }
    

    You might want to further break this down so that you initially just create the product id, and then you can create methods to add quantity or set the price.