如何在不硬編碼的情況下定義 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]

更新於: 19-2-2020

513 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

立即開始
廣告
© . All rights reserved.