将项目添加到列表

问题描述 投票:0回答:1

我需要将一个类项目添加到列表中,它必须通过键盘输入添加。我无法添加它的属性

产品类别

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


}

产品列表类

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) {
        
    }
    
    
}

还有主类,它仍在开发中,我删除了附加操作,以便让您更清楚,但第一个操作给我带来了麻烦

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

    }


有了这个我可以添加产品,但不能添加他的价格、数量和 ID,我该怎么做?

java list
1个回答
0
投票

我建议您向 Product 添加一个静态方法,以通过扫描仪获取输入并返回 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);
}
© www.soinside.com 2019 - 2024. All rights reserved.