分支语句
(1) If…else语句
格式: if(布尔表达式)
语句1;
else
语句2;
If-else-if形式
If(布尔表达式1)
语句1;
else if(布尔表达式2)
语句2;
else if(布尔表达式3)
语句3;
……
else{语句n};
public class Test { public static void main(String args[]){
int x = 30;
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 语句”); } } }
每个else总是与离它最近的if配对使用
(2) 多选一switch语句
格式:
Switch(表达式)
case valuel:
处理语句1;
Break;
case valuel:
处理语句2;
Break;
case valuel:
处理语句3;
Break;
default:
处理语句n;
public class Test {
public static void main(String args[]){
int i = 1;
switch(i){
case 0: System.out.println(“0”);
case 1: System.out.println(“1”);
case2: System.out.println(“2”);
default: System.out.println(“default”);
}
}
}
Break可写可不写
表达式的结果类型只能为byte/short/int/char型
循环结构
(1) for循环:
格式:
for(初始化;循环条件;迭代部分){
循环体;
}
for的嵌套:
for(表达式1; 表达式2; 表达式3){
for(表达式1;表达式2;表达式3){
语句;
public class fortest {
public static void main(String args[]){
int sum=0;
for(int i=0;i<=100;i++){
if(i%2==0){
System.out.println(i);
sum+=i;
}
}
System.out.println(“总和为:”+sum);
}
}
}
}
(2) while循环:
格式:while(循环条件){
循环体;
public static void main(String[] args) {
int i = 1;
int n = 1;
while(i <= 10) {
n=n*i;
i++;
System.out.println(“10的阶乘结果为:”+n);
}
(3) do…while循环:
格式:do{
循环体
}while(循环条件);
- public static void main(String[] args) {
- int i = 1;
- int n = 1;
- while(i <= 10) {
- n=n*i;
- i++;
- }
- System.out.println(“10的阶乘结果为:”+n);
先执行循环体,执行完后才判断循环条件
Break和continue