java中數組輸出的方式


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM