如果声明没有按预期执行

时间:2015-12-02 23:33:46

标签: c#

我有一些问题要触发if语句,我有5个选项,最后一个是else,除了数字1,2,3,4之外的所有东西都应该触发else,但即使这些数字都是触发它。

代码:

char choice = (char)Console.Read();

// choosing an option
if (choice == 1) // if user input == 1
{
    Console.WriteLine("Insert World's name: ");
}
else if (choice == 2) //if user input == 2
{
    Console.WriteLine("Loading World");
}
else if (choice == 3) //if user input == 3
{
    Console.WriteLine("Audio");
    Console.WriteLine("Graphics");
    Console.WriteLine("Controller");
    Console.WriteLine("Tutorial");
}
else if (choice == 4) //if user input == 4
{
    Console.WriteLine("You sure ?");
}
else
{
    Console.WriteLine("Choose a valid option"); // if any option of above is not trigged then do this
}

1 个答案:

答案 0 :(得分:0)

正如评论者已经指出的那样,数字字符不是数字1 != '1'。我不会跟着那个,我想你已经收到了那个消息。

由于这是为了与用户交互而使用Console.ReadKey方法获取按键可能更清晰,更有用。返回值是一个结构,其中包含有关按下的键的更多信息,包括修饰键等。不是与字符进行比较,而是有一个枚举命名每个键。

这就是我解决问题的方法:

string worldName = string.Empty;

// wait for keypress, don't display it to the user
// If you want to display it, remove the 'true' parameter
var input = Console.ReadKey(true);

// test the result
if (input.Key == ConsoleKey.D1 || input.Key == ConsoleKey.NumPad1)
{
    Console.Write("Insert World's name: ");
    worldName = Console.ReadLine();
}
else if (input.Key == ConsoleKey.D2 || input.Key == ConsoleKey.NumPad2)
{
    Console.WriteLine("Loading World: {0}", worldName);
}

等等。

它允许你做的事情,Console.Read方法没有,是处理不是字母数字的按键。例如,如果您想使用功能键:

// F1
if (input.Key == ConsoleKey.F1)
{
    Console.Write("Insert World's name: ");
    worldName = Console.ReadLine();
}
// F2
else if (input.Key == ConsoleKey.F2)
{
    Console.WriteLine("Loading World: {0}", worldName);
}

当然还有处理键盘修饰符:

// Shift-F1
if (input.Key == ConsoleKey.F1 && input.Modifiers == ConsoleModifiers.Shift)
{
    Console.Write("Insert World's name: ");
    worldName = Console.ReadLine();
}
// F2 with any comnination of modifiers that does not include Alt
// (F2, Shift-F2, Ctrl-F2, Ctrl-Shift-F2)
else if (input.Key == ConsoleKey.F2 && !input.Modifiers.HasFlag(ConsoleModifiers.Alt))
{
    Console.WriteLine("Loading World: {0}", worldName);
}
相关问题