• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
lamber
博客园    首页    新随笔       管理    订阅  订阅

Java程序流程控制之switch

java基础之流程控制(二)

 二、分支控制语句 switch Statement

       Java中有一个和if语句比较相似的分支控制语句叫switch ,它在有一系列固定值做分支时使用效率要比if-else方式效率高(别急,等一下再告诉你为什么效率高)。

       先看一个例子:假设我们不考虑闰年的话,我们如何知道一个月有多少天?先用if-else的方式来实现:

java代码:

  1. public class demo2 { 
  2. public static void main(String[] args) { 
  3. int month=9; 
  4. if(month==1){ 
  5. System.out.println(month+"月有31天"); 
  6. }else if(month==2){ 
  7. System.out.println(month+"月有28天"); 
  8. }else if(month==3){ 
  9. System.out.println(month+"月有31天"); 
  10. }else if(month==4){ 
  11. System.out.println(month+"月有30天"); 
  12. }else if(month==5){ 
  13. System.out.println(month+"月有31天"); 
  14. }else if(month==6){ 
  15. System.out.println(month+"月有30天"); 
  16. }else if(month==7){ 
  17. System.out.println(month+"月有31天"); 
  18. }else if(month==8){ 
  19. System.out.println(month+"月有31天"); 
  20. }else if(month==9){ 
  21. System.out.println(month+"月有30天"); 
  22. }else if(month==10){ 
  23. System.out.println(month+"月有31天"); 
  24. }else if(month==11){ 
  25. System.out.println(month+"月有30天"); 
  26. }else if(month==12){ 
  27. System.out.println(month+"月有31天"); 
  28. }else{ 
  29. System.out.println("没有这个月份吧"); 
  30. } 
  31. } 
  32. }
复制代码

       接下来我们使用switch语句重新实现一次:

java代码:
  1. public class demo2 { 
  2. public static void main(String[] args) { 
  3. int month = 9; 
  4. switch (month) { 
  5. case 1: 
  6. System.out.println(month + "月有31天"); 
  7. break; 
  8. case 2: 
  9. System.out.println(month + "月有28天"); 
  10. break; 
  11. case 3: 
  12. System.out.println(month + "月有31天"); 
  13. break; 
  14. case 4: 
  15. System.out.println(month + "月有30天"); 
  16. break; 
  17. case 5: 
  18. System.out.println(month + "月有31天"); 
  19. break; 
  20. case 6: 
  21. System.out.println(month + "月有30天"); 
  22. break; 
  23. case 7: 
  24. System.out.println(month + "月有31天"); 
  25. break; 
  26. case 8: 
  27. System.out.println(month + "月有31天"); 
  28. break; 
  29. case 9: 
  30. System.out.println(month + "月有30天"); 
  31. break; 
  32. case 10: 
  33. System.out.println(month + "月有31天"); 
  34. break; 
  35. case 11: 
  36. System.out.println(month + "月有30天"); 
  37. break; 
  38. case 12: 
  39. System.out.println(month + "月有31天"); 
  40. break; 
  41. default: 
  42. System.out.println("没有这个月份吧"); 
  43. break; 
  44. } 
  45. } 
  46. }
复制代码

       1、留意switch格式的写法
       标准且合法的格式:

1.png

想要获得成功,首先要自己相信自己,再者要赢得周围朋友的信任!
posted @ 2010-12-21 13:21  android5k  阅读(1443)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3