如何在 Java 中列印陣列的內容?


一般來說,陣列是儲存多個相同資料型別變數的容器。它們是固定大小的,大小在建立時確定。陣列中的每個元素都由從 0 開始的數字定位。

您可以使用名稱和位置訪問陣列的元素,如下所示:

System.out.println(myArray[3]);
//Which is 1457

在 Java 中建立陣列

在 Java 中,陣列被視為引用型別,您可以使用 new 關鍵字類似於物件建立陣列,並使用索引填充它,如下所示:

int myArray[] = new int[7];
myArray[0] = 1254;
myArray[1] = 1458;
myArray[2] = 5687;
myArray[3] = 1457;
myArray[4] = 4554;
myArray[5] = 5445;
myArray[6] = 7524;

或者,您可以直接在花括號內分配值,用逗號 (,) 分隔它們,如下所示:

int myArray = { 1254, 1458, 5687, 1457, 4554, 5445, 7524};

列印陣列的內容

您可以列印陣列的內容

  • **逐個元素** - 您可以訪問陣列的第一個元素作為 myArray[0],第二個元素作為 myArray[1],依此類推,使用這些表示法,您可以逐個元素列印陣列內容,如下所示:
public class PrintingArray {
   public static void main(String args[]) {
      //Creating an array
      int myArray[] = new int[7];
      //Populating the array
      myArray[0] = 1254;
      myArray[1] = 1458;
      myArray[2] = 5687;
      myArray[3] = 1457;
      myArray[4] = 4554;
      myArray[5] = 5445;
      myArray[6] = 7524;
      //Printing Contents one by one
      System.out.println("Contents of the array: ");
      System.out.println(myArray[0]);
      System.out.println(myArray[1]);
      System.out.println(myArray[2]);
      System.out.println(myArray[3]);
      System.out.println(myArray[4]);
      System.out.println(myArray[5]);
      System.out.println(myArray[6]);
   }
}

輸出

Contents of the array:
1254
1458
5687
1457
4554
5445
7524
  • **使用 for 迴圈** - 而不是逐個元素列印,您可以使用 for 迴圈迭代索引,從 0 開始到陣列的長度 (ArrayName.length),並在每個索引處列印元素。
public class PrintingArray {
   public static void main(String args[]) {
      //Creating an array
      int myArray[] = new int[7];
      //Populating the array
      myArray[0] = 1254;
      myArray[1] = 1458;
      myArray[2] = 5687;
      myArray[3] = 1457;
      myArray[4] = 4554;
      myArray[5] = 5445;
      myArray[6] = 7524;
      //Printing Contents using for loop
      System.out.println("Contents of the array: ");
      for(int i=0; i<myArray.length; i++) {
         System.out.println(myArray[i]);
      }
   }
}

輸出

Contents of the array:
1254
1458
5687
1457
4554
5445
7524
  • **使用 Arrays 類** - java.util 包的 Arrays 類提供了一個名為 toString() 的方法,它接受一個數組(所有型別)並列印給定陣列的內容。
import java.util.Arrays;
public class PrintingArray {
   public static void main(String args[]) {
      //Creating an array
      int myArray[] = new int[7];
      //Populating the array
      myArray[0] = 1254;
      myArray[1] = 1458;
      myArray[2] = 5687;
      myArray[3] = 1457;
      myArray[4] = 4554;
      myArray[5] = 5445;
      myArray[6] = 7524;
      //Printing Contents using for loop
      System.out.println("Contents of the array: ");
      System.out.println(Arrays.toString(myArray));
   }
}

輸出

Contents of the array:
[1254, 1458, 5687, 1457, 4554, 5445, 7524]

更新於: 2020-07-02

462 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告