02_Java流程控制

Huang Po-Hsuan

105.07.12

只整理易出錯或小重點,並非教學

switch

public class Switch {
    public static void main(String[] args){
        int x = 1;
        switch(x){
            case 1:
                System.out.println("1");
                break;
            case 2:
                System.out.println("2");
                break;
            default:
                break;
        }
    }
}

x 的型別 :

byte、char、short、int、String

皆會轉成 int 進行比較,其中 String 較特別,會用到 2 次 switch

run:
1

迴圈 label 使用

public class LabeInLoop {
    public static void main(String[] args){
        OUTER_LOOP://label
        for(int i = 0; i < 10; i++){
            INNER_LOOP://label
            for(int j = 0; j < 10; j++){
                if(i == 2)
                    continue OUTER_LOOP;
                else if(i == 8)
                    break OUTER_LOOP;
                else if(j == 3)
                    continue INNER_LOOP;
                else if(j == 7)
                    break INNER_LOOP;
                else 
                    System.out.println("i = "+i+" ,j = "+j);
            }
        }
    }
}
run:
i = 0 ,j = 0
i = 0 ,j = 1
i = 0 ,j = 2
i = 0 ,j = 4
i = 0 ,j = 5
i = 0 ,j = 6
i = 1 ,j = 0
i = 1 ,j = 1
i = 1 ,j = 2
i = 1 ,j = 4
i = 1 ,j = 5
i = 1 ,j = 6
i = 3 ,j = 0
i = 3 ,j = 1
i = 3 ,j = 2
i = 3 ,j = 4
i = 3 ,j = 5
i = 3 ,j = 6
i = 4 ,j = 0
i = 4 ,j = 1
i = 4 ,j = 2
i = 4 ,j = 4
i = 4 ,j = 5
i = 4 ,j = 6
i = 5 ,j = 0
i = 5 ,j = 1
i = 5 ,j = 2
i = 5 ,j = 4
i = 5 ,j = 5
i = 5 ,j = 6
i = 6 ,j = 0
i = 6 ,j = 1
i = 6 ,j = 2
i = 6 ,j = 4
i = 6 ,j = 5
i = 6 ,j = 6
i = 7 ,j = 0
i = 7 ,j = 1
i = 7 ,j = 2
i = 7 ,j = 4
i = 7 ,j = 5
i = 7 ,j = 6

foreach (走訪)

public class ForeachTest {
    public static void main(String[] args){
        String list[] = new String[3];      
        list[0] = "Hello";
        list[1] = "World";
        list[2] = "OuO";
        for(String s:list){//走訪
            System.out.println(s);
        }
    }
}
run:
Hello
World
OuO

輸入

import java.util.Scanner;

public class ScannerTest {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        int num = 0;
        while(num != 10){
            System.out.println("輸入:");
            num = scanner.nextInt();
            System.out.println(num);
        }
    }
}
run:
輸入:
4
4
輸入:
3
3
輸入:
10
10