方式1:遍歷輸出
public class Main { public static void main(String[] args) { int[] ns = { 1, 4, 9, 16, 25 }; for (int i=0; i<ns.length; i++) { int n = ns[i]; System.out.println(n); } } }
方式2:for each循環
public class Main { public static void main(String[] args) { int[] ns = { 1, 4, 9, 16, 25 }; for (int n : ns) {//注意是直接將ns數組的值送到n里面去了 System.out.println(n); } } }
注意:在for (int n : ns)
循環中,變量n
直接拿到ns
數組的元素,而不是索引。
顯然for each
循環更加簡潔。但是,for each
循環無法拿到數組的索引,因此,到底用哪一種for
循環,取決於我們的需要。
方式3:使用Java標准庫提供的Arrays.toString()
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] ns = { 1, 1, 2, 3, 5, 8 }; System.out.println(Arrays.toString(ns)); } }