mmmm0303 2020-05-19 14:18 采纳率: 64.7%
浏览 227
已结题

用HashSet模拟一个网上购物车

用HashSet模拟一个网上购物车。要求:从键盘输入5个商品的编号、名称、单价、购买数量,将这些信息存入一个HashSet,(如果编号相同,则可以在数量上加1,不能重复存入购物车)然后将该HashSet作为参数调用方法getSum(HashSet items),该方法用于计算商品的总价并返回。

  • 写回答

1条回答 默认 最新

  • threenewbee 2020-05-19 15:43
    关注
    import java.util.HashMap;
    import java.util.Scanner;
    class books
    {
        String name;
        double price;
        int number;
    }
    public class bookshop {
        static double getSum(HashMap<Integer, books> books)
        {
            books b=new books();
            double s=0;
            for(int i=0;i<books.size();i++)
            {
                b=(books) books.get(i);
                s+=(b.price*b.number);
            }
            return s;
        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            HashMap<Integer, books> m=new HashMap<Integer, books>();
            Scanner sc=new Scanner(System.in);
            books books=new books();
            System.out.print("Please input the book`s number:");
            int n=sc.nextInt();
            for(int i=0;i<n;i++)
            {
                System.out.println("Please input the "+(i+1)+" th book`s name:");
                books.name=sc.next();
                System.out.print("Please input the "+(i+1)+" th book`s price:");
                books.price=sc.nextDouble();
                System.out.print("Please input the "+(i+1)+" th book`s number:");
                books.number=sc.nextInt();
                m.put(i, books);
            }
            double s=getSum(m);
            System.out.print("The total prices of books is:"+s);
        }
    
    }
    
    

    https://blog.csdn.net/waitig1992/article/details/12883685

    评论

报告相同问题?