Java培训:增强for循环、switch

作者:操作系统

阅读目录

  • 增强for循环
  • switch

增强for循环

Java5引入了一种主要用于数组的增强型for循环。

例子

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(',');
        }
    }
}

金冠53777,结果

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

switch

:switch语句中的变量类型只能为byte、short、int或者char。

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);
    }
}

本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-08/134456.htm

金冠53777 1

本文由金冠53777-金冠娱乐53777-Welcome发布,转载请注明来源

关键词: