选择结构(no.2)

选择结构(no.2)

switch语句

格式:

switch(变量/表达式){

case 字面值1:语句块1;break;

case 字面值2:语句块2;break;

case 字面值n:语句块n;break;

default:语句块n+1;

}

注意事项:

表达式的值:byte,int,short,char

  • JDK15之后,加入了枚举类型
  • JDK1.7之后,加入了String类型
  • break可以中断switch语句的执行
  • default:所有情况都不匹配的时候,执行该语句块
例1:输入数字1-7,输出对应星期数
package cn.tedu.day02;

import java.util.Scanner;

public class switch01 {

public static void main(String[] args){
	
	Scanner sc = new Scanner(System.in);
	System.out.println("请输入数字(1-7):");
	int day = sc.nextInt();
	switch(day){
	case 1:
		System.out.println("星期一");
		break;
	case 2:
		System.out.println("星期二");
		break;
	case 3:
		System.out.println("星期三");
			break;
	case 4:
		System.out.println("星期四");
		break;
	case 5:
		System.out.println("星期五");
		break;
	case 6:
		System.out.println("星期六");
		break;
	case 7:
		System.out.println("星期日");
		break;
	default:
		System.out.println("输如有误,请重新输入");
		break;
	}
}
}

在这里插入图片描述

例2:根据输入的年份和月份,判断该月有多少天

思路:

  • 1.使用scanner用法;
    三步:导包,创建对象,接收数据
  • 2.使用变量
    年份:year,月份:month,天:day
  • 3.涉及到平闰年的判断,二月份单独考虑;使用switch语句进行
法一:
package cn.tedu.day02;
import java.util.Scanner;

public class text21 {
	public static void main(String[ ] args){
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入年份:");
		int year = sc.nextInt();
		System.out.println("请输入月份:");
		int month = sc.nextInt();
		//闰年2月有29天,其余月份与平年相同
		if(month<1 || month>12){
		System.out.println("您的输入有误,请重新输入");	//月份的范围是1-12
			
	}else if(month==2){
		if(year%4==0&&year%100!=0||year%400==0){
			System.out.println(year+"年"+month+"月有29天");
			
		}else{
			System.out.println(year+"年"+month+"月有28天");
		}
	}else {
		switch(month){
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			System.out.println(year+"年"+month+"月有31天");
			break;
		default:System.out.println(year+"年"+month+"月有30天");
		}
	}
	sc.close();
}
}
法二:
package cn.tedu.day02;
import java.util.Scanner;

public class text22 {
	public static void main(String[ ] args){
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入年份:");
		int year = sc.nextInt();
		System.out.println("请输入月份:");
		int month = sc.nextInt();
		int day=31;
		//闰年2月有29天,其余月份与平年相同
		switch(month){
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			System.out.println(year+"年"+month+"月有"+day+"天");
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			day=30;
			System.out.println(year+"年"+month+"月有"+day+"天");
			break;
		case 2:
			day=(year % 4 == 0 && year % 100 != 0 || year % 400==0 ) ? 29 : 28 ;
			System.out.println(year+"年"+month+"月有"+day+"天");
			break;
		default:System.out.println("您的输入有误,请重新输入");
		}
		sc.close();
	}
}

两种方法得到的结果相同
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44871499/article/details/89946167
今日推荐