java如何输入数组
输入数组的方法
在Java中,输入数组可以通过多种方式实现,具体取决于输入来源(如用户输入、文件读取等)。以下是几种常见的方法:
使用Scanner类从控制台输入
通过Scanner类可以方便地从控制台读取用户输入的数组数据。以下是一个示例代码:

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入数组长度: ");
int length = scanner.nextInt();
int[] array = new int[length];
System.out.println("请输入数组元素:");
for (int i = 0; i < length; i++) {
array[i] = scanner.nextInt();
}
System.out.println("输入的数组为:");
for (int num : array) {
System.out.print(num + " ");
}
scanner.close();
}
}
使用BufferedReader类从控制台输入
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("请输入数组长度: ");
int length = Integer.parseInt(reader.readLine());
int[] array = new int[length];
System.out.println("请输入数组元素:");
String[] input = reader.readLine().split(" ");
for (int i = 0; i < length; i++) {
array[i] = Integer.parseInt(input[i]);
}
System.out.println("输入的数组为:");
for (int num : array) {
System.out.print(num + " ");
}
reader.close();
}
}
从文件中读取数组
如果需要从文件中读取数组数据,可以使用Scanner或BufferedReader类:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner fileScanner = new Scanner(new File("input.txt"));
int length = fileScanner.nextInt();
int[] array = new int[length];
for (int i = 0; i < length; i++) {
array[i] = fileScanner.nextInt();
}
System.out.println("从文件读取的数组为:");
for (int num : array) {
System.out.print(num + " ");
}
fileScanner.close();
}
}
使用命令行参数输入
可以通过命令行参数传递数组数据:
public class Main {
public static void main(String[] args) {
int[] array = new int[args.length];
for (int i = 0; i < args.length; i++) {
array[i] = Integer.parseInt(args[i]);
}
System.out.println("从命令行输入的数组为:");
for (int num : array) {
System.out.print(num + " ");
}
}
}
运行命令示例:
java Main 1 2 3 4 5
注意事项
- 输入数据时需确保数据类型匹配,避免输入错误导致程序异常。
- 使用
Scanner或BufferedReader时,注意关闭资源以防止内存泄漏。 - 处理文件输入时,确保文件路径正确且文件存在。






