检查用户输入是黑色、绿色还是红色.C#.

本文关键字:红色 用户 输入 黑色 检查 | 更新日期: 2023-09-27 18:28:24

我正在开发一个程序,我希望我的用户输入以下颜色之一(红色,绿色或黑色(。但我被困住了。

到目前为止,我所做的是这样的

Console.Write("Color To Bet on: ");
string tempColor = Console.ReadLine();
while (String.IsNullOrWhiteSpace(tempColor))
{
    Console.Write("The color can't be null.");
    tempColor = Console.ReadLine().ToLower();
}

但是我如何确保我的用户输入我想要的颜色,我已经尝试摆弄字符串。包含方法,但到目前为止尚未取得任何成功。

检查用户输入是黑色、绿色还是红色.C#.

当您允许用户提供自由文本时,您永远无法控制用户输入的内容。您可以做的是向GUI提供带有单选按钮或列表之类的结构,用户必须从中选择。

在您的情况下,最简单的方法是声明用户可以键入的颜色数组,并且每次都将其与用户提供的颜色进行比较:

string[] allowedInput = new string[]{"black", "green", "red"};
Console.Write("Color To Bet on: ");
string tempColor = Console.ReadLine().ToLower();
while ((String.IsNullOrWhiteSpace(tempColor)) || (!allowedInput.Contains(tempColor)))
{
    Console.WriteLine(String.Format("Invalid color. Allowed colors are : {0}.", String.Join(", ", allowedInput)));
    tempColor = Console.ReadLine().ToLower();
}

你可以声明一个枚举并使用Enum.TryParse

enum Color { Black, Green, Red };
Console.Write("Color To Bet on: ");
string tempColor = Console.ReadLine();
Color color;
// Enum.TryParse will try to parse the user's input
// and if it fails, it will return false and will ask from the user to 
// enter a valid color.
while (!Enum.TryParse(tempColor, out color))
{
    Console.Write("You should peak one color from Black, Green and Red.");
    tempColor = Console.ReadLine();
}

你可以做这样的事情。

   var colorList = new List<string>(){"red","black","green"};
            Console.Write("Color To Bet on: ");
            string tempColor;
            bool isValid =false;
            do
            {
                tempColor = Console.ReadLine();
                isValid = colorList.Any(item => item == tempColor);
                Console.WriteLine("Please enter a valid Color i.e" + string.Join(",",colorList.ToArray()));
            }while(!isValid);

虚拟证明版本:

    public static ConsoleColor ReadColor()
    {
        string tmp = tmp = Console.ReadLine().Trim().ToLower();
        switch (tmp)
        {
            case "red": return ConsoleColor.Red;
            case "green": return ConsoleColor.Green;
            case "black": return ConsoleColor.Black;
            default:
                throw new InvalidOperationException("Invalid input - " + tmp);
        }
    }

扩展Ian的评论:

您应该创建有效颜色的enum并使用Enum.TryParse解析用户输入

示例代码

public enum MyColor
{
    Black,
    Green,
    Red
}

并按如下方式修改代码:

        Console.Write("Color To Bet on: ");
        string tempColor = Console.ReadLine();
        bool success = false;
        while (!success)
        {
            if (string.IsNullOrEmpty(tempColor))
            {
                success = false;
                Console.Write("The color can't be null.");
                tempColor = Console.ReadLine();
                continue;
            }
            tempColor = tempColor.First().ToString().ToUpper() + tempColor.Substring(1); //e.g. 'black' will not convert to MyColor.Black
            MyColor selectedColor;
            success = Enum.TryParse<MyColor>(tempColor, out selectedColor);
            if (!success)
            {
                Console.WriteLine("You should enter 'Black', 'Green' or 'Red'!");
                tempColor = Console.ReadLine();
            }
        }
暂时

忽略你的代码...您可以检查变量是否具有某些值。凭借if语句的魔力:

if (tempColor == "Red")
{
    // Do red stuff
}

您可能还对 switch 语句感兴趣,该语句可能允许您处理多个值:

switch (tempColor)
{
    case "Black":
        // Do black stuff
        break;
    case "Blue":
        // Do blue stuff
        break;
    case "Red":
        // Do red stuff
        break;
}

甚至将它们组合在一起:

switch (tempColor)
{
    case "Black":
    case "Blue":
        // Do black or blue stuff
        break;
    case "Red":
        // Do red stuff
        break;
}

现在,您的代码:

Console.Write("Color To Bet on: ");
string tempColor = Console.ReadLine();
while (String.IsNullOrWhiteSpace(tempColor))
{
    Console.Write("The color can't be null.");
    tempColor = Console.ReadLine().ToLower();
}

您可能希望在每次输入之前说出"下注的颜色",因此:

Console.Write("Color To Bet on: ");
string tempColor = Console.ReadLine();
while (String.IsNullOrWhiteSpace(tempColor))
{
    Console.Write("The color can't be null.");
    Console.Write("Color To Bet on: ");
    tempColor = Console.ReadLine().ToLower();
}

您可能希望"颜色不能为空"在输入之后,并且只读取一次^1,因此:

while(true)
{
    Console.Write("Color To Bet on: ");
    string tempColor = Console.ReadLine().ToLower();
    if (String.IsNullOrWhiteSpace(tempColor))
    {
        Console.Write("The color can't be null.");
        continue;
    }
    break;
}

^1:为什么?它更易于维护,看看你的代码,你忘了在第一次调用时放ToLower。你傻,重复自己。

现在您可以添加条件:

while(true)
{
    Console.Write("Color To Bet on: ");
    string tempColor = Console.ReadLine().ToLower();
    if (String.IsNullOrWhiteSpace(tempColor))
    {
        Console.Write("The color can't be null.");
        continue;
    }
    if (tempColor != "black" && tempColor != "blue"  && tempColor != "red")
    {
        Console.Write("The color must be Black, Blue or Red");
        continue;
    }
    break;    
}

正如其他决定键入比我少的人所指出的那样,您可以使用数组来保存这些值。

string[] colors = {"black", "green", "red"};
// ...
while(true)
{
    Console.Write("Color To Bet on: ");
    string tempColor = Console.ReadLine().ToLower();
    if (String.IsNullOrWhiteSpace(tempColor))
    {
        Console.Write("The color can't be null.");
        continue;
    }
    if (!colors.Contains(tempColor))
    {
        Console.Write("The color must be Black, Blue or Red");
        continue;
    }
    break;    
}

等等,代码有问题。它仍然在消息上显示"黑色,蓝色或红色",如果您决定向数组添加新颜色而忘记将其添加到消息中怎么办?这些文本只应出现一次。此外,应事先通知用户什么是有效选项。

string[] colors = {"black", "green", "red"};
// ...
while(true)
{
    Console.WriteLine("The colors are: " + string.Join(",", colors));
    Console.Write("Color To Bet on: ");
    string tempColor = Console.ReadLine().ToLower();
    if (String.IsNullOrWhiteSpace(tempColor))
    {
        Console.Write("The color can't be null.");
        continue;
    }
    if (!colors.Contains(tempColor))
    {
        Console.Write("The color is not valid");
        continue;
    }
    break;    
}

你真的不需要第一个条件。数组上没有空或空格:

string[] colors = {"black", "green", "red"};
// ...
while(true)
{
    Console.WriteLine("The colors are: " + string.Join(",", colors));
    Console.Write("Color To Bet on: ");
    string tempColor = Console.ReadLine().ToLower();
    if (!colors.Contains(tempColor))
    {
        Console.Write("The color is not valid");
        continue;
    }
    break;    
}

我们这里的条件有一个否定,让我们颠倒过来:

string[] colors = {"black", "green", "red"};
// ...
while(true)
{
    Console.WriteLine("The colors are: " + string.Join(",", colors));
    Console.Write("Color To Bet on: ");
    string tempColor = Console.ReadLine().ToLower();
    if (colors.Contains(tempColor))
    {
        break;
    }
}

嗯......可以进一步简化:

string[] colors = {"black", "green", "red"};
// ...
string tempColor;
do
{
    Console.WriteLine("The colors are: " + string.Join(",", colors));
    Console.Write("Color To Bet on: ");
    tempColor = Console.ReadLine().ToLower();
} while (!colors.Contains(tempColor));

附录:可能值得注意的是,鉴于输入集是固定的,您可以为它们分配数字并让用户按数字选择一个。其他选项包括制作交互式菜单(是的,在控制台中(或支持自动完成文本...但我敢打赌你不在乎这个。

扩展 npintis 答案 我想添加从列表中选择颜色选项的可能性(如 GUI(:

    var options = string.Format("Choose between colors:{0}1. Black{0}2. Green{0}3. Red{0} 4. Quit", Environment.NewLine);
    var selection = char.MinValue;
    while (!char.IsDigit(selection))
    {
        Console.WriteLine(options);
        selection = Console.ReadKey().KeyChar;
        Console.Clear();
    }
    int choice = int.Parse(selection.ToString());
    switch (choice)
    {
        case 1:
            Console.WriteLine("Black");
            break;
        case 2:
            Console.WriteLine("Green");
            break;
        case 3:
            Console.WriteLine("Red");
            break;
        case 4:
            break;
    }
  List<string> validColors = new List<string>() { "red", "blue", "green" };
  string tempColor = Console.ReadLine().ToLower();
  if (validColors.Contains(tempColor))
    {
        //proceed with success code
    }
  else
    {
        // show invalid option
    }

最简单的方法是添加一个具有所需颜色的字符串表,然后检查它是否包含用户输入的字符串。

string[] colors = {"black", "green", "red"};
if (colors.Contains(tempColor.ToLower())) //dosomething
else //dosomething

试试这个:

        string[] colours = { "green", "black", "red" };
        Console.Write("Color To Bet on: ");
        string tempColor = Console.ReadLine();
        while (String.IsNullOrWhiteSpace(tempColor))
        {
            Console.Write("The color can't be null.");
            tempColor = Console.ReadLine().ToLower();
        }
        var result = Array.Exists(colours, element => element == tempColor);