我希望这段代码根据我的输入值输出 Nay 或 Yay
Console.Write("Welcome! Please Select Any Number: ");
int x = Convert.ToInt32(Console.Read());
if (x >= 10)
{
Console.WriteLine("Yay");
}
else
{
Console.WriteLine("You are Wrong");
}
我最初没有使用Convert.ToInt32函数,但无论输入的值是否违反初始条件,它都会输出You are bad。
一开始没有使用Convert.ToInt函数,代码一直输出You bad,然后使用之后,一直输出Yay 我希望代码输出“Nay”一词,因为每当我的值小于 10 时,无论我输入什么值,输出都默认为“Yay” 如果输入的值符合条件,我希望它输出 Yay
Console.Read()
返回 int
- 这是输入流的下一个字符的 Unicode 值。您想要使用 Console.ReadLine()
,它返回用户输入的字符串(尽管用户还必须按键盘上的 Enter
/Return
键)。
此外,如果用户输入无法转换为
int
的内容(例如 banana
)怎么办?您想使用 int.TryParse
而不是 Convert.ToInt32
,这样您的程序在这种情况下就不会崩溃。
Console.Write("Welcome! Please enter any number: ");
var userInput = Console.ReadLine();
if(int.TryParse(userInput, out var x)
{
if(x >= 10)
{
Console.WriteLine("Yay");
}
else
{
Console.WriteLine("You are Wrong");
}
}
else
{
Console.WriteLine($"Can't parse {userInput} as an int.");
}