Java 中如何使用增強for循環
增強型for循環在遍歷一個數組的時候會更加快捷
步驟 1 : 增強型for循環
注:增強型for循環只能用來取值,卻不能用來修改數組里的值
public class HelloWorld {
public static void main(String[] args) {
int values [] = new int[]{18,62,68,82,65,9};
//常規遍歷
for (int i = 0; i < values.length; i++) {
int each = values[i];
System.out.println(each);
}
//增強型for循環遍歷
for (int each : values) {
System.out.println(each);
}
}
}
練習: 最大值
(用增強型for循環找出最大的那個數)
答案:
public class HelloWorld {
public static void main(String[] args) {
int values [] = new int[]{18,62,68,82,65,9};
//數組中的內容是
for (int each : values) {
System.out.print(each+" ");
}
System.out.println();
int max = -1;
for (int each : values) {
if(each>max)
max = each;
}
System.out.println("最大的一個值是:"+max);
}
}