Java從鍵盤(pán)輸入數(shù)組可以通過(guò)以下幾種方式實(shí)現(xiàn):
1. 使用Scanner類(lèi):
`java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("請(qǐng)輸入數(shù)組的長(zhǎng)度:");
int length = scanner.nextInt();
int[] array = new int[length];
System.out.println("請(qǐng)輸入數(shù)組的元素:");
for (int i = 0; i < length; i++) {
array[i] = scanner.nextInt();
}
System.out.println("輸入的數(shù)組為:");
for (int num : array) {
System.out.print(num + " ");
}
}
上述代碼中,首先使用Scanner類(lèi)獲取用戶(hù)輸入的數(shù)組長(zhǎng)度,然后創(chuàng)建一個(gè)對(duì)應(yīng)長(zhǎng)度的整型數(shù)組。接下來(lái),通過(guò)循環(huán)獲取用戶(hù)輸入的每個(gè)數(shù)組元素,并將其存入數(shù)組中。遍歷數(shù)組并輸出。
2. 使用BufferedReader類(lèi):
`java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("請(qǐng)輸入數(shù)組的長(zhǎng)度:");
int length = Integer.parseInt(reader.readLine());
int[] array = new int[length];
System.out.println("請(qǐng)輸入數(shù)組的元素:");
for (int i = 0; i < length; i++) {
array[i] = Integer.parseInt(reader.readLine());
}
System.out.println("輸入的數(shù)組為:");
for (int num : array) {
System.out.print(num + " ");
}
}
上述代碼中,通過(guò)BufferedReader類(lèi)實(shí)現(xiàn)從鍵盤(pán)讀取用戶(hù)輸入。首先創(chuàng)建一個(gè)BufferedReader對(duì)象,然后使用readLine()方法獲取用戶(hù)輸入的數(shù)組長(zhǎng)度,并將其轉(zhuǎn)換為整型。接下來(lái),創(chuàng)建一個(gè)對(duì)應(yīng)長(zhǎng)度的整型數(shù)組,并通過(guò)循環(huán)獲取用戶(hù)輸入的每個(gè)數(shù)組元素。遍歷數(shù)組并輸出。
3. 使用Console類(lèi)(僅適用于命令行環(huán)境):
`java
import java.io.Console;
public class Main {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.out.println("無(wú)法獲取Console對(duì)象,請(qǐng)?jiān)诿钚协h(huán)境下運(yùn)行程序。");
return;
}
System.out.print("請(qǐng)輸入數(shù)組的長(zhǎng)度:");
int length = Integer.parseInt(console.readLine());
int[] array = new int[length];
System.out.println("請(qǐng)輸入數(shù)組的元素:");
for (int i = 0; i < length; i++) {
array[i] = Integer.parseInt(console.readLine());
}
System.out.println("輸入的數(shù)組為:");
for (int num : array) {
System.out.print(num + " ");
}
}
上述代碼中,通過(guò)System.console()方法獲取Console對(duì)象,然后使用readLine()方法獲取用戶(hù)輸入的數(shù)組長(zhǎng)度,并將其轉(zhuǎn)換為整型。接下來(lái),創(chuàng)建一個(gè)對(duì)應(yīng)長(zhǎng)度的整型數(shù)組,并通過(guò)循環(huán)獲取用戶(hù)輸入的每個(gè)數(shù)組元素。遍歷數(shù)組并輸出。
以上是三種常用的從鍵盤(pán)輸入數(shù)組的方式,你可以根據(jù)具體需求選擇適合的方法來(lái)實(shí)現(xiàn)。
千鋒教育擁有多年IT培訓(xùn)服務(wù)經(jīng)驗(yàn),開(kāi)設(shè)Java培訓(xùn)、web前端培訓(xùn)、大數(shù)據(jù)培訓(xùn),python培訓(xùn)、軟件測(cè)試培訓(xùn)等課程,采用全程面授高品質(zhì)、高體驗(yàn)教學(xué)模式,擁有國(guó)內(nèi)一體化教學(xué)管理及學(xué)員服務(wù),想獲取更多IT技術(shù)干貨請(qǐng)關(guān)注千鋒教育IT培訓(xùn)機(jī)構(gòu)官網(wǎng)。