Значение, не изменяющееся при вводе другого параметра в инструкции switch

#c#

#c#

Вопрос:

ребята, мне просто нужна помощь. Извините, я новичок в программировании на C #. И моя проблема в том, что когда я ввожу значение, допустим, я ввожу 2, я хочу распечатать: (Пока вставлено: 0 из 23.) Но что происходит, так это то, что оно показывает то же значение soda, которое равно 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;
            }
  

Ответ №1:

Вы используете интерполяцию строк с неправильным именем переменной

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

Вместо того, чтобы каждый раз печатать значение soda, вы должны печатать значение 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}");
        }
  

Ответ №2:

Неправильная переменная в строке вывода: {soda} вместо {itemPrice}

Ответ №3:

В вашем случае вы должны проверить if (itemPrice < soda) после switch (userChoice)

Ответ №4:

Это то, что вы хотели сделать:

 class Program
{
    static void Main(string[] args)
    {
        List<Item> items = new List<Item>()
        {
            new Item
            {
                Name = "Soda",
                Price = 30
            },
            new Item
            {
                Name = "Juice",
                Price = 23
            },
            new Item
            {
                Name = "Water",
                Price = 15
            }
        };

        while (true)
        {
            //MENU
            Log("Available Items:");
            for(int i = 0; i < items.Count; i  )
            {
                Log("{0}. {1} = P{2}", i, items[i].Name, items[i].Price);
            }
            Console.WriteLine();

            bool isInputValid = false;
            string userChoice = string.Empty;
            int chosenIndex = 0;

            while (isInputValid == false)
            {
                try
                {
                    Log("Choose your Item:");
                    userChoice = Console.ReadLine();
                    chosenIndex = int.Parse(userChoice);
                    if(chosenIndex < 0 || chosenIndex >= items.Count)
                    {
                        throw new ArgumentOutOfRangeException();
                    }
                    isInputValid = true;
                }
                catch
                {
                    Log("Invalid choice!");
                }
            }

            Item chosenItem = items[chosenIndex];
            bool isPriceReached = false;
            string userInsertedMoney = string.Empty;
            int insertedMoney = 0;

            while (isPriceReached == false)
            {
                try
                {
                    Log("P{0} of P{1} needed Money for {2} inserted, waiting for more...", insertedMoney, chosenItem.Price, chosenItem.Name);
                    userInsertedMoney = Console.ReadLine();
                    insertedMoney  = int.Parse(userInsertedMoney);
                    isPriceReached = insertedMoney >= chosenItem.Price;
                }
                catch
                {
                    Log("Invalid money!");
                }
            }

            Log("Here is your {0} with a rest of {1} money.{2}", chosenItem.Name, insertedMoney - chosenItem.Price, Environment.NewLine);
        }
    }

    private static void Log(string message, params object[] args)
    {
        Console.WriteLine(string.Format(message, args));
    }
}

public class Item
{
    public string Name { get; set; }
    public int Price { get; set; }
}