如何透過從 Java 中的使用者獲取輸入來一次填充一個值到陣列中?


要從使用者處讀取資料,請建立一個掃描器類。使用 nextInt() 方法從使用者處讀取要建立的陣列大小。建立一個指定大小的陣列。在迴圈中從使用者處讀取值,並將其儲存在上面建立的陣列中。

示例

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-Feb-2020

6 千次觀看

啟程你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.