Java 如果 ... 否则 示例
现实生活中的例子
此示例演示如何使用 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; // Is this a positive or negative number?
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.");
}
确定一个数字是偶数还是奇数。
示例
int myNum = 5;
if (myNum % 2 == 0) {
System.out.println(myNum + " is even");
} else {
System.out.println(myNum + " is odd");
}