IF分支结构
If主要是针对关系表达式进行判断处理的分支操作。对于分支结构主要有三类:
一类:
if(布尔表达式){
条件满足时执行;
}
二类:
if(布尔表达式){
条件满足时执行;
}
else{
条件不满足时执行;
}
三类:
if (布尔表达式) {
条件满足时执行 ;
} else if (布尔表达式) {
条件满足时执行 ;
} else if (布尔表达式) {
条件满足时执行 ;
} [else {
条件不满足时执行 ;
}]
例子:
public class JavaDemo {
public static void main(String args[]) {
double score = 90.00 ;
if (score >= 90.00 && score <=100) {
System.out.println(“优等生。”) ;
} else if(score >=60 && score < 90) {
System.out.println(“良等生。”) ;
} else {
System.out.println(“差等生。”) ;
}
}
}
输出:优等生
SWITCH开关语句
switch中可以判断的只能够是数据(int、char、枚举、String),定义如下:
switch(数据){
case数值:{
数值满足时执行;
[break]
case数值:{
数值满足时执行;
[break]
[default:
所有判断数值不满足时执行;
[break;]
]
}
switch在设计时候,如果在每一个case后面没有追加break语句,那么会一直会执行到后续代码结束或者遇见break。
例子:
public class JavaDemo {
public static void main(String args[]) {
int ch = 2 ;
switch (ch) {
case 2 :{
System.out.println(“设置的内容是2。”) ;
break ;
}
case 1 : {
System.out.println(“设置的内容是1。”) ;
break ;
}
default : {
System.out.println(“没有内容满足。”) ;
break ;
}
}
}
}
输出:设置的内容是2。
while循环
某一段代码重复执行,提供while语句实现,有两种形式:
形式1:
while(布尔表达式){
条件满足时执行;
修改循环条件;
}
形式2:
do {
条件满足时执行;
修改循环条件;
} while (布尔表达式);
区别:while先循环判断后执行,do while 先执行后循环判断
例子:求1到100的和
public class JavaDemo {
public static void main(String args[]) {
int sum = 0 ; // 保存最终的计算总和
int num = 1 ; // 进行循环控制
do { // 循环的执行条件
sum += num ; // 累加
num ++ ; // 修改循环条件
} while (num <= 100) ;
System.out.println(sum) ;
}
}
输出:5050
for循环
定义语法如下:
for (定义循环的初始化数值;循环判断;修改循环数据){
循环语句的执行;
}
例子:求1到100的和
public class JavaDemo {
public static void main(String args[]) {
int sum = 0 ; // 保存最终的计算总和
for (int x = 1 ; x <= 100 ; x ++) {
sum += x ; // 累加
}
System.out.println(sum) ;
}
}