共計 439 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用 for 循環來遍歷數組并輸出數組中的元素。下面是一個示例代碼:
public class Main {public static void main(String[] args) {int[] arr = {1, 2, 3, 4, 5};
// 使用普通 for 循環輸出數組元素
System.out.println(" 使用普通 for 循環輸出數組元素:");
for (int i = 0; i < arr.length; i++) {System.out.println(arr[i]);
}
// 使用增強 for 循環輸出數組元素
System.out.println(" 使用增強 for 循環輸出數組元素:");
for (int num : arr) {System.out.println(num);
}
}
}
在上面的示例中,首先定義了一個整型數組 arr
,然后使用普通 for 循環和增強 for 循環分別遍歷數組并輸出數組中的元素。增強 for 循環簡化了循環的書寫,特別適用于遍歷數組或集合等容器類型的數據結構。
丸趣 TV 網 – 提供最優質的資源集合!
正文完