if/else语句中的语法错误

本文关键字:语法 错误 语句 else if | 更新日期: 2023-09-27 18:25:46

我对c#非常陌生,在处理基本程序时,我收到了这个错误(只有错误赋值、调用、增量、减量、等待和新对象表达式可以用作语句),无法弄清楚它出现的原因。

if (pizzaDiameter >= 12 && pizzaDiameter < 16)// begin nested if statement
{
    Console.WriteLine("A" + pizzaDiameter + "will yield 8 slices.");
}
else if (pizzaDiameter >= 16 && pizzaDiameter < 24)//Second pizza diameter range
{
    Console.WriteLine("A" + pizzaDiameter + "will yield 12 slices.");
}
else if (pizzaDiameter >= 24 && pizzaDiameter < 30)
{
    Console.WriteLine("A" + pizzaDiameter + "will yield 16 slices.");
}
else (pizzaDiameter >= 24 && pizzaDiameter <= 30)
{
    Console.WriteLine("A" + pizzaDiameter + "will yield 24 slices.");
}
else // pizza diameter was not a whole number
{
    Console.WriteLine("Pizza diameter must be between 12-36 inclusive.");// Error appears here.
}
else //pizza diameter must be between 12-36
{
    Console.WriteLine("Pizza diameter must be a whole number.");
}

if/else语句中的语法错误

您的控制结构有问题,即您只有一个if(),但有三个else

此外,试着思考这个问题,你会注意到你可以显著简化整个结构(也可以跳过许多检查):

if (pizzaDiameter < 12) // All diameters below 12 will use this branch.
    Console.WriteLine("Your pizza seems to be too small.");
else if (pizzaDiameter < 16) // You don't have to ensure it's bigger than 12, since those smaller already picked the branch above.
    Console.WriteLine("A diameter of " + pizzaDiameter + " will yield 8 slices");
else if (pizzaDiameter < 24) // Again you won't have to care for less than 16.
    Console.WriteLine("A diameter of " + pizzaDiameter + " will yield 12 slices");
// ...
else
    Console.WriteLine("Your pizza seems to be too big.");