2.1 选择结构
2.1.1 if
//写法
//第一种
if (判断条件){
语句体;
}
//第二种
if (判断条件){
语句体1;
}else{
语句体2;
}
//第三种
if (判断条件1){
语句1;
}else if(条件判断2){
语句2;
}
....
}else if(条件判断n){
语句n;
}else{
语句n+1;
}
一个demo
public class Demo04if {
public static void main(String[] args){
int score = 100;
if (score<0 || score>100){
System.out.println("错误");
}else if (score>85){
System.out.println("优秀");
}else if (score>60){
System.out.println("及格");
}
}
}
2.1.2 switch
switch(表达式){
case 常量值1:
语句1;
break;
case 常量值2:
语句2;
break;
default:
语句3;
break;
}
SwitchNotice
- 多个case后面的常量不能相同
- switch数据类型基本类型只能是 byte/short/char/int,引用类型 String,enum枚举
- switch格式比较灵活
一个demo
public class Demo05switch {
public static void main(String[] args){
switch (5%3){
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
break;
default:
System.out.println("n");
break;
}
}
}
2.2 循环结构
2.2.1 for
//写法
for (初始化表达式1;布尔表达式2;步进表达式4){
循环体3;
}
2.2.2 while和do while
//while写法
while(布尔表达式1){
循环体;
步进表达式;
}
//do while写法
初始化表达式1
do{
循环体1;
步进表达式;
}while(布尔表达式2);
一个demo
public class Demo06circulation {
public static void main(String[] args) {
demoWhile();
demoDoWhile();
}
public static void demoWhile() {
int n = 3;
System.out.println("while");
while (n >= 0) {
System.out.println(n);
n=n-1;
}
}
public static void demoDoWhile() {
int n = 3;
System.out.println("do while");
do {
System.out.println(n);
n=n-1;
} while (n >= 0);
}
}