Java 条件语句
if、if...else、if...else if...else 与嵌套条件。
if 语句
if (booleanExpr) runs the block when true. The condition must be a boolean: if (1) does not compile, unlike C/C++.
public class IfDemo {
public static void main(String[] args) {
int x = 10;
if (x < 20) {
System.out.println("This is if statement");
}
}
}This is if statementif...else 语句
True takes the if branch, false takes else — exactly one runs. Always keep the braces even for one statement; omitting them invites bugs when code is added later.
public class IfElse {
public static void main(String[] args) {
int x = 30;
if (x < 20) {
System.out.println("This is if statement");
} else {
System.out.println("This is else statement");
}
}
}This is else statementif...else if...else 语句
Multiple branches are tested in order and the first true one wins, so order conditions from specific to general. The final else is a catch-all and may be omitted.
public class IfElseIf {
public static void main(String[] args) {
int x = 30;
if (x == 10) {
System.out.println("Value of X is 10");
} else if (x == 20) {
System.out.println("Value of X is 20");
} else if (x == 30) {
System.out.println("Value of X is 30");
} else {
System.out.println("This is else statement");
}
}
}Value of X is 30嵌套 if 语句
An if block may contain another if. An else always binds to the nearest unmatched if, so always brace nested conditions to avoid ambiguity.
public class NestedIf {
public static void main(String[] args) {
int x = 30;
int y = 10;
if (x == 30) {
if (y == 10) {
System.out.println("X = 30 and Y = 10");
}
}
}
}X = 30 and Y = 10if 语句
if (布尔表达式) 为真时执行大括号内的代码。Java 的条件必须是 boolean,写 if (1) 会编译报错 —— 这点与 C/C++ 不同。
public class IfDemo {
public static void main(String[] args) {
int x = 10;
if (x < 20) {
System.out.println("This is if statement");
}
}
}This is if statementif...else 语句
条件为真走 if 分支,为假走 else 分支,二者必居其一。只有一个分支时也必须写完整的大括号,否则后续加代码容易出错。
public class IfElse {
public static void main(String[] args) {
int x = 30;
if (x < 20) {
System.out.println("This is if statement");
} else {
System.out.println("This is else statement");
}
}
}This is else statementif...else if...else 语句
多分支按顺序判断,命中第一个为真的分支后其余全部跳过,所以条件要从特殊到一般排列。最后的 else 兜底,可以省略。
public class IfElseIf {
public static void main(String[] args) {
int x = 30;
if (x == 10) {
System.out.println("Value of X is 10");
} else if (x == 20) {
System.out.println("Value of X is 20");
} else if (x == 30) {
System.out.println("Value of X is 30");
} else {
System.out.println("This is else statement");
}
}
}Value of X is 30嵌套 if 语句
if 块里可以再写 if。else 永远匹配最近的、尚未配对的 if(就近原则),所以嵌套时务必加大括号,避免歧义。
public class NestedIf {
public static void main(String[] args) {
int x = 30;
int y = 10;
if (x == 30) {
if (y == 10) {
System.out.println("X = 30 and Y = 10");
}
}
}
}X = 30 and Y = 10