条件语句
Java 中的条件语句允许程序根据条件的不同执行不同的代码块。一个 if 语句包含一个布尔表达式和一条或多条语句。
if 语句
if大于小于判断
如果布尔表达式的值为 true,则执行 if 语句中的代码块,否则执行 else 语句块后面的代码。
public class 条件语句 {
public static void main(String[] args) {
int x = 10;
if (x < 20) {
System.out.print("这是 if 语句");
}
if…else语句
//if 语句后面可以跟 else 语句,当 if 语句的布尔表达式值为 false 时,else 语句块会被执行。
if (x < 20) {
System.out.print("这是 if 语句");
} else {
System.out.print("这是 else 语句");
}
if…else if…else 语句
//if...else if...else 语句
if (x == 10) {
System.out.print("Value of X is 10");
} else if (x == 20) {
System.out.print("Value of X is 20");
} else if (x == 30) {
System.out.print("Value of X is 30");
} else {
System.out.print("这是 else 语句");
}
}
}
Java switch case 语句
switch case 语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支。
public class Test {
public static void main(String args[]){
//char grade = args[0].charAt(0);
char grade = 'C';
switch(grade)
{
case 'A' :
System.out.println("优秀");
break;
case 'B' :
case 'C' :
System.out.println("良好");
break;
case 'D' :
System.out.println("及格");
break;
case 'F' :
System.out.println("你需要再努力努力");
break;
default :
System.out.println("未知等级");
}
System.out.println("你的等级是 " + grade);
}
}
运行结果:
---------------------------------------------------------
良好
你的等级是 C