分类
1.顺序结构
2.分支结构
3.循环结构
分支结构
1.if语句
if (条件)
{ 语句体;}
2.if…else…语句
if (条件)
{ 语句体1;}
else
{ 语句体2;}
3.if…else if…else 语句
if (条件1)
{ 语句体1;}
else if(条件2)
{ 语句体2;}
else if(条件3)
{ 语句体3;}
...
else
{末语句体}
4.switch语句
switch (x){
case 值1:
语句体1;
break;
case 值2:
语句体2;
break;
case 值3:
语句体3;
break;
default:
末语句体;
break;
}
注意:
①x可以是表达式也可以是确定的值,x等于哪个值就执行哪个case。
②default可以没有
循环结构
1.for循环(先判断再循环)
与c++一致
示例;
public class test {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
System.out.println(i);
}
}
}
结果:依次输出1,2,3,4,5
2.while循环
与c++一致
示例:
public class test {
public static void main(String[] args) {
int j = 1;
while(j<=5){
System.out.println(j);
j++;
}
}
}
3.do…while…循环(先循环一次再判断)
与c++一致(无论while里面是正确还是错误,do里面的循环体先执行一次)
示例:
public class test {
public static void main(String[] args) {
int j = 1;
do{
System.out.println(j);
j++;
}while(j<=5);
}
}
4.for死循环
示例:
public class test {
public static void main(String[] args) {
for(;;){
System.out.println('p');
}
}
}
5.while死循环
示例:
public class test {
public static void main(String[] args) {
while(true){
System.out.println("p");
}
}
}
6.do…while…死循环
示例:
public class test {
public static void main(String[] args) {
do{
System.out.println("p");
}while(true);
}
}