Java學習——加強for循環、switch

加強for循環

Java5引入了一種主要用於數組的加強型for循環。數組

例子spa

public class ForTest {
    public static void main(String args[]){
        int [] numbers = {1, 3, 5, 7, 2, 4, 6, 8};
        for (int x: numbers){
            System.out.print(x);
            System.out.print(",");
        }
        System.out.println();

        String [] names = {"Jihite", "David", "Tom"};
        for (String name: names){
            System.out.print(name);
            System.out.print(',');
        }
    }
}

結果code

1,3,5,7,2,4,6,8,
Jihite,David,Tom,

switch

:switch語句中的變量類型只能爲byte、short、int或者char。blog

public class ForTest {

    public static void main(String args[]){
        //char grade = args[0].charAt(0);
        char grade = 'B';

        switch(grade)
        {
            case 'A' :
                System.out.println("Excellent!");
                break;
            case 'B' :
            case 'C' :
                System.out.println("Well done");
                break;
            case 'D' :
                System.out.println("You passed");
            case 'F' :
                System.out.println("Better try again");
                break;
            default :
                System.out.println("Invalid grade");
        }
        System.out.println("Your grade is " + grade);
    }
}
相關文章
相關標籤/搜索