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