You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#计算器程序输入校验优化:实现错误输入时重复问询

Fixing Your C# Calculator with Retry Logic

Got it, let's tweak your calculator to give users proper retry opportunities when they enter invalid numbers or operators—no more bailing early or only catching errors at the end. Here's the adjusted code, along with explanations of the key changes:

Modified Code

using System;

namespace Calculator
{
    class Program
    {
        static void Main()
        {
            while (true)
            {
                double num1 = 0;
                bool isValidNum1 = false;
                
                // Retry loop for first number input
                while (!isValidNum1)
                {
                    Console.Write("Enter a number: ");
                    string number1 = Console.ReadLine();
                    
                    if (double.TryParse(number1, out num1))
                    {
                        Console.WriteLine("First number is " + num1);
                        isValidNum1 = true;
                    }
                    else if (number1.ToLower() == "quit")
                    {
                        Console.WriteLine("Goodbye...");
                        return; // Exit the program immediately
                    }
                    else
                    {
                        Console.WriteLine("That is not a valid number. Please try again.");
                    }
                }

                string operation = "";
                bool isValidOperation = false;
                
                // Retry loop for operator input
                while (!isValidOperation)
                {
                    Console.Write("Enter an operation (+ - * / ^): ");
                    operation = Console.ReadLine();
                    
                    if (operation.ToLower() == "quit")
                    {
                        Console.WriteLine("Goodbye...");
                        return;
                    }
                    // Check if operation is one of the valid options
                    else if (operation == "+" || operation == "-" || operation == "*" || operation == "/" || operation == "^")
                    {
                        isValidOperation = true;
                    }
                    else
                    {
                        Console.WriteLine("That is not a valid operation. Please try again.");
                    }
                }

                double num2 = 0;
                bool isValidNum2 = false;
                
                // Retry loop for second number input
                while (!isValidNum2)
                {
                    Console.Write("Enter second number: ");
                    string number2 = Console.ReadLine();
                    
                    if (double.TryParse(number2, out num2))
                    {
                        Console.WriteLine("Second number is " + num2);
                        isValidNum2 = true;
                    }
                    else if (number2.ToLower() == "quit")
                    {
                        Console.WriteLine("Goodbye...");
                        return;
                    }
                    else
                    {
                        Console.WriteLine("That is not a valid number. Please try again.");
                    }
                }

                // Perform calculation now that all inputs are valid
                if (operation == "+")
                {
                    Console.WriteLine($"Result: {num1 + num2}");
                }
                else if (operation == "-")
                {
                    Console.WriteLine($"Result: {num1 - num2}");
                }
                else if (operation == "*")
                {
                    Console.WriteLine($"Result: {num1 * num2}");
                }
                else if (operation == "/")
                {
                    // Bonus: Add division by zero check!
                    if (num2 == 0)
                    {
                        Console.WriteLine("Error: Cannot divide by zero.");
                    }
                    else
                    {
                        Console.WriteLine($"Result: {num1 / num2}");
                    }
                }
                else if (operation == "^")
                {
                    Console.WriteLine($"Result: {Math.Pow(num1, num2)}");
                }

                Console.WriteLine("\n--- Ready for next calculation? Enter 'quit' at any time to exit ---\n");
            }
        }
    }
}

Key Changes Explained

  • Per-input retry loops: We added separate while loops for the first number, operator, and second number. Each loop keeps asking for input until the user enters a valid value or types "quit".
  • Early exit with return: Instead of break (which only exits the inner loop), we use return to immediately exit the Main method (and thus the program) when the user types "quit".
  • Valid operation check upfront: The operator loop validates the input right away, so the user gets immediate feedback instead of waiting until after entering the second number.
  • Added division by zero check: A small bonus to handle a common edge case that would cause a runtime error otherwise.
  • Clearer feedback messages: Updated error messages to tell the user exactly what went wrong and to try again.

This way, users can correct their input without having to restart the entire program, and invalid entries are caught immediately when they're made.

内容的提问来源于stack exchange,提问作者Tom.Achki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:42:33