如何在 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 年 2 月 19 日

514 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.