2015-12-02 53 views
-5

我有一些问题来触发if语句,我有5个选项最后一个是其他和每个事物,但数字1,2,3,4应该触发其他但即使这些数字触发它。如果没有按照预期执行语句

代码:

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 
} 
+10

提示:'1'是不一样的''1'' – clcto

+0

提示: '1'= 0x31 = 49 –

+2

我想你会发现[本文](http://www.joelonsoftware.com/articles/Unicode.html)关于字符编码非常有见地。 – cubrr

回答

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