如何使用陣列大小動態度宣告 Java 陣列?


要動態宣告陣列大小,請使用 Scanner 類從使用者那裡讀取所需的整數值,然後使用給定值建立一個數組

示例

import java.util.Arrays;
import java.util.Scanner;

public class PopulatingAnArray {
   public static void main(String args[]) {
      System.out.println("Enter the required size of the array :: ");
      Scanner s = new Scanner(System.in);
      int size = s.nextInt();
      int myArray[] = new int [size];
      System.out.println("Enter the elements of the array one by one ");
     
      for(int i = 0; i<size; i++) {
         myArray[i] = s.nextInt();
     }
     System.out.println("Contents of the array are: "+Arrays.toString(myArray));
   }
}

輸出

Enter the required size of the array ::
5
Enter the elements of the array one by one
78
96
45
23
45
Contents of the array are: [78, 96, 45, 23, 45]

更新於: 2020-02-19

2 千次 + 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.