如何在 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]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP