java如何从键盘输入数组
从键盘输入数组的方法
在Java中,可以通过多种方式从键盘输入数组。以下是几种常见的方法:
使用Scanner类读取固定大小的数组
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] array = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
System.out.println("Array elements are:");
for (int num : array) {
System.out.print(num + " ");
}
scanner.close();
}
}
使用BufferedReader类读取数组
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("Enter the size of the array: ");
int size = Integer.parseInt(reader.readLine());
int[] array = new int[size];
System.out.println("Enter the elements of the array separated by space:");
String[] input = reader.readLine().split(" ");
for (int i = 0; i < size; i++) {
array[i] = Integer.parseInt(input[i]);
}
System.out.println("Array elements are:");
for (int num : array) {
System.out.print(num + " ");
}
reader.close();
}
}
使用Scanner类读取字符串数组
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
String[] array = new String[size];
scanner.nextLine(); // Consume the newline
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextLine();
}
System.out.println("Array elements are:");
for (String str : array) {
System.out.println(str);
}
scanner.close();
}
}
使用命令行参数输入数组
public class Main {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No arguments provided.");
return;
}
System.out.println("Array elements are:");
for (String arg : args) {
System.out.print(arg + " ");
}
}
}
注意事项
- 使用
Scanner时,注意处理输入缓冲区中的换行符。 - 使用
BufferedReader时,需要处理IOException。 - 输入数据时,确保数据类型与数组类型匹配,避免
NumberFormatException。
以上方法可以根据具体需求选择适合的方式从键盘输入数组。







