A:总结switch语句和if语句的各自使用场景

  • switch建议判断固定值的时候用
  • if建议判断区间或范围的时候用

    B:案例演示

    • 分别用switch语句和if语句实现下列需求:
      • 键盘录入月份,输出对应的季节
  1. import java.util.Scanner;
  2. class Test3_SwitchIf {
  3. public static void main(String[] args) {
  4. /*
  5. * 键盘录入月份,输出对应的季节
  6. 一年有四季
  7. 3,4,5春季
  8. 6,7,8夏季
  9. 9,10,11秋季
  10. 12,1,2冬季
  11. */
  12. Scanner sc = new Scanner(System.in); //创建键盘录入对象
  13. System.out.println("请输入月份");
  14. int month = sc.nextInt(); //将键盘录入的结果存储在month
  15. /*switch (month) {
  16. case 3:
  17. case 4:
  18. case 5:
  19. System.out.println(month + "月是春季");
  20. break;
  21. case 6:
  22. case 7:
  23. case 8:
  24. System.out.println(month + "月是夏季");
  25. break;
  26. case 9:
  27. case 10:
  28. case 11:
  29. System.out.println(month + "月是秋季");
  30. break;
  31. case 12:
  32. case 1:
  33. case 2:
  34. System.out.println(month + "月是冬季");
  35. break;
  36. default:
  37. System.out.println("对不起没有对应的季节");
  38. break;
  39. }*/
  40. //用if语句来完成月份对应季节
  41. if (month > 12 || month < 1) {
  42. System.out.println("对不起没有对应的季节");
  43. }else if (month >= 3 && month <= 5) {
  44. System.out.println(month + "月是春季");
  45. }else if (month >= 6 && month <= 8) {
  46. System.out.println(month + "月是夏季");
  47. }else if (month >= 9 && month <= 11) {
  48. System.out.println(month + "月是秋季");
  49. }else {
  50. System.out.println(month + "月是冬季");
  51. }
  52. }
  53. }