检查是用户输入黑色,绿色或红色。 C#

时间:2015-12-30 08:17:43

标签: c#

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

到目前为止,我所做的是

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();
}

但是我怎样才能确保我的用户使用我想要的颜色,我已经尝试用字符串摆弄。包含方法,但到目前为止还没有取得任何成功。

10 个答案:

答案 0 :(得分:7)

当您允许用户提供免费文本时,您永远无法控制用户输入的内容。您可以做的是提供一个带有单选按钮的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();
}

答案 1 :(得分:5)

您可以声明枚举并使用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();
}

答案 2 :(得分:1)

你可以做这样的事情。

   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);

答案 3 :(得分:1)

虚拟打样版本:

    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);
        }
    }

答案 4 :(得分:1)

扩展伊恩的评论:

您应该创建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();
            }
        }

答案 5 :(得分:1)

暂时忽略您的代码......您可以检查变量是否具有某些值。借助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();
}

你可能想要&#34;颜色打赌&#34;在每次输入之前都要说,所以:

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();
}

你可能想要那个&#34;颜色不能为空。&#34;在输入之后,也只读一次^ 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;    
}

等等,代码有问题。它仍然说&#34;黑色,蓝色或红色&#34;如果您决定向数组中添加新颜色并忘记将其添加到邮件中,该怎么办?这些文本只应出现一次。此外,应事先通知用户有效选项是什么。

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;    
}

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

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));

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

答案 6 :(得分:1)

扩展 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;
    }

答案 7 :(得分:0)

  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
    }

答案 8 :(得分:0)

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

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

答案 9 :(得分:-2)

试试这个:

        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);