1 if分支
1.1 定义
if语句使用最多,?"if…else"表示:“如果满足某种条件,就进行某种处理”
1.2 if结构
1.2.1 案列
判断是否要去度假
@Test
public void testIF3() {
int ans = JOptionPane.showConfirmDialog(null, "你一定要去度假嗎?");
if (ans==JOptionPane.YES_OPTION) {//ans==,不是ans=
System.out.println("要去");
}
if (ans==JOptionPane.NO_OPTION) {
System.out.println("不去");
}
if (ans==JOptionPane.CANCEL_OPTION) {
System.out.println("取消");
}
}
1.3 if…else分支
1.3.1 案列
比较两个数字大小
/**
* 按顺序执行的if
*/
@Test
public void testIF() {
Scanner sc = new Scanner(System.in);
System.out.print("输入一个数字");
int a = Integer.parseInt(sc.nextLine());
System.out.print("输入一个数字");
int b = Integer.parseInt(sc.nextLine());
if (a>b) {
System.out.println(a+">"+b);
}
System.out.println("第一个if結束");
if (a<b) {
System.out.println(a+"<"+b);
}
System.out.println("第二个if結束");
if (a==b){
System.out.println(a+"="+b);
}
System.out.println("第三个if結束");
sc.close();
}
1.4 if…elseif…else分支
1.4.1 案列
语法
int x = 3;
if(x > 3){
System.out.println("x > 3")
}else if(x == 3){
System.out.println("x >= 3")
}else{
System.out.println("x < 3")
}
判断学生成绩
/**
* 判斷學生成績等級
*/
@Test
public void ifElseIfTest() {
Scanner sc = new Scanner(System.in);
System.out.print("輸入學生成績:");
int a = Integer.parseInt(sc.nextLine());
if(a<0 || a>100) {
System.out.print("輸入錯誤,請檢查");
}else if(a>89 && a<=100) {//[90,100]
System.out.print("A+優秀");
}else if(a>=80){//[80,89]
System.out.print("A-良好");
}else if(a>=60){//[60,79]
System.out.print("B+合格");
}else {//[0,59]
System.out.print("C不合格");
}
}
2 switch分支
2.1 定义
如果多分支的条件是证书或这字符串,可以使用switch
2.2 案列
/**
* 用swich判断学生成绩等级
*/
@Test
public void test() {
Scanner sc = new Scanner(System.in);
System.out.print("输入学生成绩");
int source = sc.nextInt();
int key = source/10;//设置一个key,A等级[90,100];91~99除10都是9,因为int/int=int,小数点会自动舍去;
switch(key) {
case 10:
case 9:
System.out.print("A");
break;
case 8:
System.out.print("B");
break;
case 7:
case 6:
System.out.print("C");
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
System.out.print("D");
break;
default:
System.out.print("输入不合法");
break;
}
}