1. 顺序结构
public class sequence {
public static void main(String[] args) {
System.out.println("1");
System.out.println("2");
}
}
2.选择结构
if
①if语句
/*if(关系表达式){
语句体;
}*/
public class Choice {
public static void main(String[] args) {
System.out.println("成年了吗");
int num=16;
if (age>=18){
System.out.println("成年了")
}
System.out.println("未成年");
}
}
/*if--else
if(关系表达式) {
语句体1;
} else {
语句体2;
}*/
②if–else
if(关系表达式) {
语句体1;
} else {
语句体2;
}
③if–else if–else
if (判断条件1) {
执行语块1;
}else if (判断条件2) {
执行语块2;
}
...
} else if (判断条件n){
执行语块n;
} else {
执行语句
}
switch
switch(表达式) {
case 常量值1:
语句体1;
break;
case 常量值2:
语句体2;
break;
...
default:
语句体n+1;
break;
}
注意事项:
1.多个case后面的数值不可以重复
2.switch后面小括号当中只能是byte/short/char/int、引用数据类型:String字符串,eunm枚举
for
for(初始化表达式;布尔表达式;步进表达式) {
循环体
}
public class HelloWorld {
public static void main(String[] args) {
for(int i=15;i>=10;i--) {
System.out.println(i);
}
}
}
do-while
初始化语块
do{
循环体
}while(条件判断);
public class HelloWorld {
public static void main(String[] args) {
int i;
i = 1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
三种循环的区别:
如果条件从未满足,for、while执行0次,但是do-while至少执行一次
for变量只能在内部使用,while、do-while出循环后还可继续使用
continue
一旦执行,立刻跳过当前循环剩余内容,马上开始下一循环(和break大致相同)
死循环
while(ture){
循环体
}