C#中IF语句添加多条件时出现编译错误求助
问题描述
我写了一个用于检查用户是否符合俱乐部入场年龄的小程序,同时要在未成年场次时判断用户年龄是否合适或超龄,但出现了以下编译错误:
Compilation error (line 19, col 20): ) expected
Compilation error (line 19, col 87): ; expected
Compilation error (line 19, col 87): } expected
Compilation error (line 21, col 4): 'else' cannot start a statement.
Compilation error (line 21, col 4): Syntax error, '(' expected
Compilation error (line 21, col 4): Invalid expression term 'else'
Compilation error (line 21, col 4): ) expected
Compilation error (line 21, col 4): Invalid expression term 'else'
Compilation error (line 21, col 4): ; expected
Compilation error (line 19, col 12): 'bool' is a type, which is not valid in the given context
我已经检查了分号、括号和大括号,但还是搞不懂问题出在哪,以下是我的代码:
using System; public class Program { public static void Main() { int clubAgeMin = 18; int clubUAgeMin =(clubAgeMin - 2); int clubUAgeMax =17; int userAge =20; Boolean isUNight =false; if (userAge >= clubAgeMin && isUNight == false) { Console.WriteLine("Welcome to the club!"); } else if (userAge < clubAgeMin && isUNight == false) { Console.WriteLine("Sorry but your under 18, please come back when we have a underage's night"); } else if (Boolean isUNight == true && userAge >= clubUAgeMin && userAge < clubUAgeMax) { Console.WriteLine("Wlcome to the club's underage night!"); } else if (userAge > clubUAgeMax) { Console.WriteLine("Sorry buddy but your too old for the underage night"); } else if (userAge < clubUAgeMin) { Console.WriteLine("Sorry buddy but your too young for the underage night, comeback when you are older"); } } }
错误原因分析
- 核心语法错误:第19行的
else if条件中,错误地给变量isUNight添加了类型声明Boolean。在条件表达式里,直接使用已声明的变量即可,不需要重复指定类型。另外,布尔值判断可以简化,isUNight == true直接写成isUNight更符合C#编码规范。 - 拼写错误:代码里存在几处拼写问题,比如
your应改为you're(表示"你是"),Wlcome应为Welcome,comeback应拆分为come back。 - 逻辑漏洞:部分未成年场次的分支没有判断
isUNight是否为true,可能导致逻辑混乱;同时userAge < clubUAgeMax应该改为userAge <= clubUAgeMax,因为clubUAgeMax是17,应该允许17岁用户入场。
修正后的代码
using System; public class Program { public static void Main() { int clubAgeMin = 18; int clubUAgeMin = clubAgeMin - 2; int clubUAgeMax = 17; int userAge = 20; bool isUNight = false; // C#惯例使用小写bool if (userAge >= clubAgeMin && !isUNight) { Console.WriteLine("Welcome to the club!"); } else if (userAge < clubAgeMin && !isUNight) { Console.WriteLine("Sorry but you're under 18, please come back when we have an underage's night"); } else if (isUNight && userAge >= clubUAgeMin && userAge <= clubUAgeMax) { Console.WriteLine("Welcome to the club's underage night!"); } else if (isUNight && userAge > clubUAgeMax) { Console.WriteLine("Sorry buddy but you're too old for the underage night"); } else if (isUNight && userAge < clubUAgeMin) { Console.WriteLine("Sorry buddy but you're too young for the underage night, come back when you are older"); } } }
内容的提问来源于stack exchange,提问作者Dima

