簡體   English   中英

我怎樣才能讓我的用戶輸入只接受特定的符號?

[英]How can I make it so that my user input only accepts specific symbols?

我正在制作一個簡單的計算器應用程序,我一直在絞盡腦汁,因為每當用戶輸入錯誤的選擇時,我都會嘗試循環問題。

Console.WriteLine("\nChoose an operation:");
Console.WriteLine("     ------------------  ");
Console.WriteLine("    | Addition:       + |");
Console.WriteLine("    | Subtraction:    - |");
Console.WriteLine("    | Multiplication: x |");
Console.WriteLine("    | Division:       / |");
Console.WriteLine("     ------------------  \n");

operators = Console.ReadLine();

while (operators != "+" || operators != "+" || operators != "+" || operators != "+")
{
    Console.WriteLine("Please input correct operation: ");
    operators = Console.ReadLine();
}

如果您替換邏輯,可能會更容易理解:

operator = Console.ReadLine();

var acceptableOperators = "+ - x /".Split();
while (!acceptableOperators.Contains(operator))
{
  Console.WriteLine("Please input one of: " + string.Join(" or ", acceptableOperators);
  operator = Console.ReadLine();
}

關鍵部分是邏輯變成

“雖然這個可接受的運算符列表不包含用戶輸入”,或者換句話說,“而用戶輸入的內容不存在於可接受的運算符列表中”

這很容易擴展,只需向字符串添加更多運算符,錯誤消息就會自動更改。 它也支持多字符運算符

請注意,如果變量不是集合或數組,則不應使用以復數形式命名的變量(調用變量operator


你原來的邏輯是錯誤的,原因有兩個:

  • 你犯了一個重復"+"四次的復制粘貼錯誤
  • 兩個當人們說“檢查這盞燈不是藍色或紅色”時,他們的意思是!(light == blue || light == red) - 括號很重要。 你也可以說“檢查這個燈不是藍色也不是紅色”來表示同樣的事情 - 在 C# 中它是light != blue && light != red ,但你不能說“light is not blue OR light is not red”因為無論光線是什么顏色,它總是正確的。

因為(至少說英語)人類傾向於說第一種形式(“檢查光不是藍色或紅色”)在演講中沒有任何明顯的括號,它往往會在心理上引導新手想要寫light != blue || red light != blue || red然后他們記得 c# 必須為每次檢查重復變量,以便它變light != blue || light != red light != blue || light != red當它應該是!(light == blue || light == red)

它應該是 && 而不是 ||,所以用戶只能輸入 + 或 - 或 x 或 /

while (operators != "+" && operators != "-" && operators != "x" && operators != "/")
{
    Console.WriteLine("Please input correct operation: ");
    operators = Console.ReadLine();
}

您的代碼邏輯可以簡化並變得更加用戶友好(無需在每次選擇運算符時都要求“Enter”):

        char key;
        while (true)
        {
            key = Console.ReadKey().KeyChar;
            if ("+-x/".Contains(key)) break;
            Console.WriteLine("\nPlease input correct operation: ");
        }
        Console.WriteLine($"You pressed {key}");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM