【Java案例】超市购物

案例介绍:

编写一个超市购物程序,在一家超市有牙刷、毛巾、水杯、苹果和香蕉五种商品,用户输入商品序列号进行商品购买,用户输入购买数量后计算出所需要花费的钱,一次购买结束后,需要用户输入“Y”或“N”,“Y”代表继续购买,“N”代表购物结束,此时需要计算并输出本次购物的总计花费的钱。商品价格如下表所示。

 运行结果:

 完整代码:

import java.util.Scanner;

public class supermarket {
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        double toothbrush = 8.8;//牙刷
        double towel = 10;//毛巾
        double cup = 18.8;//水杯
        double apple = 12.5;//苹果
        double banana =15.5;//香蕉
        System.out.println("------------黑马小商城------------");
        System.out.println("1.牙刷的价格为:"+toothbrush+"元");
        System.out.println("2.毛巾的价格为:"+towel+"元");
        System.out.println("3.水杯的价格为:"+cup+"元");
        System.out.println("4.苹果的价格为:"+apple+"元");
        System.out.println("5.香蕉的价格为:"+banana+"元");
        System.out.println("--------------------------------");
        int item;//购买商品序列号
        int count;//购买商品的数量
        double total = 0;//购买商品总金额
        String good = "商品名";
        String goods = "商品量词";
        double price = 0;
        String choice = "Y";
        do{
            System.out.print("请输入您需要购买商品的序列号:");
            item = scanner.nextInt();
            switch (item)
            {   //将序列号对应的商品名、商品量词、商品价格分别赋值给good、goods、price
                case 1: good = "牙刷";    goods = "把";    price = toothbrush; break;
                case 2: good = "毛巾";    goods = "条";    price = towel;      break;
                case 3: good = "水杯";    goods = "个";    price = cup;        break;
                case 4: good = "苹果";    goods = "斤";    price = apple;      break;
                case 5: good = "香蕉";    goods = "斤";    price =banana;      break;
                default:
                    item=0;//若序列号输入错误,将item赋值为0
                    System.out.println("---------商品序列号输入错误---------");
            }
            if(item!=0) //序列号输入正确,执行if语句
            {   
                System.out.print("请输入您需要购买" + good + "的数量:");
                count = scanner.nextInt();
                total = total + count * price;
                System.out.println("您购买了" + good + count + goods + ",需要花费" + count * price + "元");
            }
            System.out.print("需要继续购买请输入Y,否则输入N:");
            choice = scanner.next();
            
            while(!choice.equals("Y")&&!choice.equals("N"))//若输入字母不为Y或N,则进入while循环
            {
                System.out.println("--------是否继续购买识别失败--------");
                System.out.print("需要继续购买请输入Y,否则输入N:");
                choice = scanner.next();
            }//输入"Y"循环继续,输入"N"循环退出
        }while(choice.equals("Y"));
        System.out.println("您本次购物共花费 "+total+" 元");
        System.out.println("期待您的下次光临!");
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_66697650/article/details/128586708
今日推荐