如何在 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.