JAVA分支

本文详细介绍了Java中的if、if-else、if…elseif…else分支,以及switch语句的定义、案例和用法。通过度假判断、数字比较和学生成绩等级判断,展示了这些控制结构在实际编程中的运用。
摘要由CSDN通过智能技术生成

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;
		}
		
	}
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值