【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