c# - 尝试使用 Else 语句 C# 的初学者?

标签 c# if-statement

<分区>

我是第一次参加计算机类(class)的学生,多年来我一直试图“破解”这门类(class)(我对此很陌生……抱歉!)。我似乎无法构建一个简单的 if/else 语句,如果满足条件,它会写一个肯定的响应,如果不满足,则写一个否定的响应。但我收到错误: 无效的表达式术语“else”
只有assignment、call、increment、decrement、new对象表达式才能作为语句使用

抱歉,如果这没有意义,我很困惑! :(

static void Main(string[] args)
{
    Console.WriteLine("Do you like bananas?");
    Console.ReadLine();
    if (Console.ReadLine() == "Yes") ;
    {
        Console.WriteLine("Thanks for your time!");
    }
    else;
    {
        Console.WriteLine("Oh okay.");
    }
 }
}

最佳答案

您需要删除 else 之后的分号。 通常是它的

if (condition) 
{
 //code
}
else 
{
 //code
}

如果你有不止一个条件要满足,你可以拥有

if (condition)
{
 //code
}
else if (condition 2)
{
 //code
}
else 
{
 //code
}

如果以上条件都不满足,则使用最后一个 else,这就像默认行为

此外,您不需要只有一行代码的大括号

if (condition) DoInterestingStuff();
else DoNotDoInterestingStuff();

一些示例条件(带有用于说明的不必要的 if 语句):

if (bananas == true)
if (bananas) // same as above
if (bananas != false) // not equal to false, thus true
if (totalBananas >= 10)

关于c# - 尝试使用 Else 语句 C# 的初学者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26741235/

相关文章:

linux - 如果 [ awk 'BEGIN{print 0.4*10}' > 1 -eq 0 ];然后回显是;菲

string - 将单元格内容与 Excel 中的字符串进行比较

jquery - 仅当代码中其他地方存在类时,如何应用 CSS?

c# - 使用 C#、XPath 进行 XML 解析

c# - Visual Studio 2010 更好的 C# 语法着色?

c# - 运行 .NET Core API Linux 环境启动配置文件

c# - 在Win32_Volume中设置属性

c# - 如何捕捉 C# .NET 窗体上的按键

python - 大于小于,python

java - 如何解决从四个随机生成的数字中查找最小数字时偶尔出现的错误答案