如何在 Java 中從掃描器將資料讀取到陣列中?


java.util 包的 Scanner 類提供給你像 nextInt()、nextByte()、nextFloat() 等方法,用來從鍵盤讀取資料。要讀取陣列的一個元素,請在 for 迴圈中使用這些方法

示例

 線上演示

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

public class ReadingWithScanner {
   public static void main(String args[]) {
      Scanner s = new Scanner(System.in);
      System.out.println("Enter the length of the array:");
      int length = s.nextInt();
      int [] myArray = new int[length];
      System.out.println("Enter the elements of the array:");

      for(int i=0; i<length; i++ ) {
         myArray[i] = s.nextInt();
      }

      System.out.println(Arrays.toString(myArray));
   }
}

輸出

Enter the length of the array:
5
Enter the elements of the array:
25
56
48
45
44
[25, 56, 48, 45, 44]

更新時間: 30-Jul-2019

10K+ 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.