繁体   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