[Java基础] 流程控制结构

流程控制结构

  1. if - else

      private static String checkHeartBeats(int heatBeats) {
          if (heatBeats > 100) {
              return "too fast";
          } else if (heatBeats >= 60) {
              return "normal";
          } else {
              return "too slow";
          }
      }
    
  2. switch - case

        private static String getApha(int month) {
            switch (month) {
                case 1:
                    return "One";
                case 2:
                    return "Two";
                case 3:
                    return "Three";
                case 4:
                    return "Four";
                default:
                    return "Unknown";
            }
        }
    
  3. for

        private static void forLoop() {
            for (int i = 0; i < 10; i++) {
                System.out.println(i);
            }
        }
    
  4. while

        private static void whileLoop(){
            int i = 1;
            while (i<=10){
                System.out.println(i);
                i++;
            }
        }
    
  5. do while

        private static void doWhileLoop() {
            int i = 1;
            do {
                System.out.println(i);
                i++;
            } while (i <= 50);
        }
    
  6. 嵌套循环

        private static void mutilLoop() {
            for (int j = 1; j <= 5; j++) {
                for (int i = 1; i <= j; i++) {
                    System.out.print('*');
                }
                System.out.println();
            }
        }
    
  7. break - continue

    break:结束当前循环

    continue:跳出当次循环

        private static void breakAndContinue() {
            for (int i = 1; i <= 10; i++) {
                if (i % 3 == 0) {
                    continue;
                }
                if (i % 5 == 0) {
                    break;
                }
                System.out.print(i);
            }
        }
    
  8. label 标志 跳出多重循环

        private static void breakAndContinue() {
    
            label:
            for (int j = 1; j <= 4; j++) {
                for (int i = 1; i <= 10; i++) {
                    if (i % 5 == 0) {
                        break label;
                    }
                    System.out.print(i);
                }
                System.out.println();
            }
        }
    
posted @ 2023-03-05 17:40  漫游者杰特  阅读(16)  评论(0编辑  收藏  举报