Java If ... Else 示例
实际应用示例
此示例展示了如何使用 if...else 在用户输入正确密码后"打开门":
示例
int doorCode = 1337;
if (doorCode == 1337) {
System.out.println("Correct code. The door is now open.");
} else {
System.out.println("Wrong code. The door remains closed.");
}
这个例子展示了如何使用if...else语句来判断一个数是正数还是负数:
示例
int myNum = 10; // 这是一个正数还是负数?
if (myNum > 0) {
System.out.println("The value is a positive number.");
} else if (myNum < 0) {
System.out.println("The value is a negative number.");
} else {
System.out.println("The value is 0.");
}
查询某人是否达到投票年龄:
示例
int myAge = 25;
int votingAge = 18;
if (myAge >= votingAge) {
System.out.println("Old enough to vote!");
} else {
System.out.println("Not old enough to vote.");
}
判断一个人是否达到投票年龄,以及是否是本国公民(使用嵌套的if语句):
示例
int age = 20;
boolean isCitizen = true;
if (age >= 18) {
System.out.println("Old enough to vote.");
if (isCitizen) {
System.out.println("And you are a citizen, so you can vote!");
} else {
System.out.println("But you must be a citizen to vote.");
}
} else {
System.out.println("Not old enough to vote.");
}
判断一个数是奇数还是偶数:
示例
int myNum = 5;
if (myNum % 2 == 0) {
System.out.println(myNum + " is even");
} else {
System.out.println(myNum + " is odd");
}
检查体温:
示例
int temperature = 30;
if (temperature < 0) {
System.out.println("It's freezing!");
} else if (temperature < 20) {
System.out.println("It's cool.");
} else {
System.out.println("It's warm.");
}
系统访问控制示例 - 您必须先登录,然后必须是管理员,或者拥有高安全级别(1 级或 2 级)才能获得访问权限:
示例
boolean isLoggedIn = true;
boolean isAdmin = false;
int securityLevel = 3; // 1 = highest
if (isLoggedIn && (isAdmin || securityLevel <= 2)) {
System.out.println("Access granted");
} else {
System.out.println("Access denied");
}
// Try changing securityLevel to test different outcomes:
//
// securityLevel 1 = Access granted
// securityLevel 2 = Access granted
// securityLevel 3 = Access denied
// securityLevel 4 = Access denied
//
// If isAdmin = true, access is granted.

