循环让char无法正常工作

时间:2014-01-07 02:51:08

标签: c# loops

所以,我试图创建一个循环,如果有人输入一个char它将执行。如果错了,它将不会显示选项。如果我在我的Array()方法之后的“end”末尾添加Else {Console.WriteLine("Not an option"),它也不起作用。 所以,我不完全确定我在做什么。这甚至需要循环吗?我想它会起作用吗?任何建议都会很棒。

class Program
{
    static void Main(string[] args)
    {

        string _a = "";
        constructor dick = new constructor();
        Console.WriteLine("Enter C for constructor, M for method, A for an array...");
        Console.WriteLine("Please reference source code to have full details and understanding...");
        while (_a.ToUpper() == "C" || "M" || "A")
        {
            _a = Console.ReadLine();
            if (_a.ToUpper() == "C")
            {
                Console.WriteLine(dick.a);
            }
            if (_a.ToUpper() == "M")
            {
                Shit();
            }
            if (_a.ToUpper() == "A")
            {
                Array();
            }
        }
    }

    public class constructor
    {
        public string a = "This is a constructor!";
    }
    static public void Shit()
    {
        string b = "This is a method!";
        Console.WriteLine(b);
    }
    static public void Array()
    {
        Console.WriteLine("\nHow large of an array?\n");
        string sSize = Console.ReadLine();
        int arraySize = Convert.ToInt32(sSize);
        int[] size = new int[arraySize];
        Random rd = new Random();
        Console.WriteLine();
        for (int i = 0; i < arraySize; i++)
        {
            size[i] = rd.Next(arraySize);

            Console.WriteLine(size[i].ToString());
        }

    }

}
}

1 个答案:

答案 0 :(得分:4)

而不是:

while (_a.ToUpper() == "C" || "M" || "A")

定义bool变量并:

bool control = true;

while (control)
{
    _a = Console.ReadKey();
    var character = _a.KeyChar.ToString().ToUpper();
    switch (character)
        {
            case "C":
                Console.WriteLine(dick.a);
                control = false;
                break;
            case "M":
                 control = false; 
                 Shit();
                break;
            case "A":
                 control = false;
                 Array();
                 break;
            default:
               Console.WriteLine("You entered wrong character");
               break;
        }
}

如果您想强制用户输入正确的字符,是的,您需要循环。如果输入只是一个字符,则使用Console.ReadKey而不是Console.ReadLine