if (条件){
语句;
}
else if (条件){
语句;
|
else{
语句;
}
1.2 Swich 结构
- 不加break;会让程序从目标case开一直执行到最后包括default情况下的语句
switch(表达式){
case 常量表达式1:
语句1;
break;
case 常量表达式2:
语句2;
break;
default: // 都不满足情况下用default
语句3;
}
举个例子
Scanner sc = new Scanner(System.in);
System.out.print("Please input a number between 1-3: ")
int n = sc.nextInt();
switch (n){
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
break;
case 3:
System.out.println("3");
break;
default:
System.out.println("Out of range");
}
如果不用break;
Scanner sc = new Scanner(System.in);
System.out.print("Please input a number between 1-3: ");
int n = sc.nextInt();
switch (n){
case 1:
System.out.println("1");
case 2:
System.out.println("2");
case 3:
System.out.println("3");
default:
System.out.println("Out of range");
}
当你输入2会返回如下
Please input a number between 1-3: 2 2 3 Out of range



