我试图询问输入是否是合法的数值变量.我已经尝试过这种方式(它显示错误的输出,如图所示),使用==和else(其中说其他错误)并且不知道为什么它不起作用.任何建议或其他尝试这样做的方式将非常感激.
static void start()
{
// start of broken code
Console.WriteLine("Please select a variable type");
string selection = Console.ReadLine();
if ((selection != "short") || (selection != "ushort") || (selection != "int") || (selection != "uint") || (selection != "byte") || (selection != "long") || (selection != "ulong"));
{
Console.WriteLine("That is not a correct form of variable");
Console.WriteLine("Let's try this again");
start();
}
// end of broken code
Console.WriteLine("You selected ", selection);
Console.WriteLine("Is this correct? (Y/N)");
string sure = Console.ReadLine();
if (sure == "Y")
{
Console.WriteLine("Let's begin!");
calculator();
}
else
{
Console.WriteLine("Let's try this again");
start();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:请选择一个变量类型int //我输入的内容这不是一个正确的变量形式让我们再试一次请选择一个变量类型
这一行有两个问题:
if ((selection != "short") || (selection != "ushort") || (selection != "int") || (selection != "uint") || (selection != "byte") || (selection != "long") || (selection != "ulong"));
Run Code Online (Sandbox Code Playgroud)
|| 要么 &&
这条线用简单的英语说,如果用户的选择不是"短",或者它不是"ushort"等,无论选择什么都不能同时 - 所以你总是得到这个消息"这不是一个正确的变量形式".
相反,您希望代码检查用户的选择是否"短",而不是"ushort"等.因此,如果选择与任何一种允许的可能性相匹配,您将继续执行确认步骤.
; 在if条件之后
有一;处不应该存在该行的末尾.它具有为条件体添加空块的效果,并且无论条件的结果如何,应该在条件体中的代码将始终执行.所以你的代码
if ((selection != "short") && (selection != "ushort") ... );
{
Console.WriteLine("That is not a correct form of variable");
}
Run Code Online (Sandbox Code Playgroud)
相当于
if ((selection != "short") && (selection != "ushort") ... )
{}
Console.WriteLine("That is not a correct form of variable");
Run Code Online (Sandbox Code Playgroud)
删除分号,它将按预期运行.
if ((selection != "short") && (selection != "ushort") ... )
{
Console.WriteLine("That is not a correct form of variable");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |