使用字母作为有效的用户输入(控制台项目)
本文关键字:输入 用户 控制台 项目 有效 | 更新日期: 2023-09-27 18:17:50
我正在编写一个应用程序,其中控制台询问用户一个有五个可能答案的问题(这些是a)b)c)d)e)答案。我试图找到一种方法,让控制台识别用户输入的字母,然后告诉用户答案是正确的还是错误的。这是我到目前为止所做的,尽管它似乎不起作用。如有任何帮助,不胜感激。
Console.ReadLine ();
Console.WriteLine ("Q9: Of the following, which is greater than one half?");
Console.WriteLine ("A: 2/5");
Console.WriteLine ("B: 4/7");
Console.WriteLine ("C: 4/9");
Console.WriteLine ("D: 5/11");
Console.WriteLine ("E: 6/13");
string ans9;
Console.ReadLine ();
if (ans9 == b) {
Console.WriteLine ("Correct");
} else if (ans9 != b) {
Console.WriteLine ("Incorrect");
控制台将该行读取为string
,因此您需要使用:
if (ans9 == "b")
但是你可能还想考虑一下大小写。如果用户输入B
会发生什么?
if (ans9.ToLower() == "b")
您也没有将ReadLine
的值分配给ans9
:
string ans9 = Console.ReadLine();
另一个编辑:而不是检查ans9
是否等于"b",然后检查它不等于"b"你可以使用else:
if (ans9 == "b") {
Console.WriteLine("Correct");
}
else {
Console.WriteLine("Incorrect");
}