首页 > 解决方案 > 在 switch 语句中输入其他选项时值不变

问题描述

伙计们,我只是想要一些帮助。对不起,我是 C# 编程的新手。我的问题是,当我输入一个值时,比如说我输入 2,我想打印出来:(到目前为止插入:23 个中的 0 个。)但是发生的情况是它显示了相同的苏打水值,即 30 而不是 23 .

namespace VendingMachine
{
    class Program
    {
        static void Main(string[] args)
        {
            int itemPrice = 0;
            int moneyAvailable = 0;
            int change = 0;
            int soda = 30;
            int juice = 23;
            int water = 15;
            string userChoice;

            // Menu
            Console.WriteLine();
            Console.WriteLine("1. Soda = P30");
            Console.WriteLine("2. Juice = P23");
            Console.WriteLine("3. Water = P15");
            Console.WriteLine("4. Exit");
            Console.WriteLine();

            // Values entered by the user
            Console.Write("Your choice: ");
            userChoice = Console.ReadLine();

            Console.WriteLine("================================");

// THE MAIN PROBLEM
            if (itemPrice < soda)
            {
                Console.WriteLine($"Inserted so far: P0 out of P{soda}");
            } 
            Console.Write("Enter the amount of Money!: P");
            moneyAvailable = int.Parse(Console.ReadLine());

            switch (userChoice)
            {
                case "1":
                    itemPrice = itemPrice + soda;
                    break;

                case "2":
                    itemPrice = itemPrice + juice;
                    break;

                case "3":
                    itemPrice = itemPrice + water;
                    break;

                default:
                    Console.WriteLine("Invalid. Choose 1, 2 or 3.");
                    break;
            }

标签: c#

解决方案


您正在使用带有错误变量名的字符串插值

        if (itemPrice < soda)
        {
            Console.WriteLine($"Inserted so far: P0 out of P{itemPrice}");
                                                        //   ^^^^^^^^^^ Problem is here      
        } 

而不是每次都打印苏打水的价值itemPrice

这个带有 if 条件的打印语句应该转到switch 语句的末尾

就像是,

        Console.Write("Enter the amount of Money!: P");
        moneyAvailable = int.Parse(Console.ReadLine());

        switch (userChoice)
        {
            case "1":
                itemPrice = itemPrice + soda;
                break;

            case "2":
                itemPrice = itemPrice + juice;
                break;

            case "3":
                itemPrice = itemPrice + water;
                break;

            default:
                Console.WriteLine("Invalid. Choose 1, 2 or 3.");
                break;
        }

       if (itemPrice < soda)
        {
            Console.WriteLine($"Inserted so far: P0 out of P{itemPrice}");
        }

推荐阅读