Java学习——增强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(','); } } }
结果
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); } }