java如何输入数组
输入数组的方法
在Java中,可以通过多种方式输入数组,具体取决于输入源(如控制台、文件等)和数组类型(如基本类型或对象类型)。以下是几种常见的方法:
使用Scanner从控制台输入
对于基本数据类型(如int、double等),可以使用Scanner类从控制台读取输入并填充数组。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("输入数组长度: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("输入数组元素: ");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
System.out.println("输入的数组: ");
for (int num : arr) {
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 br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("输入数组长度: ");
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
System.out.println("输入数组元素(空格分隔): ");
String[] input = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(input[i]);
}
System.out.println("输入的数组: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
输入字符串数组
如果需要输入字符串数组,可以直接使用Scanner或BufferedReader读取字符串。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("输入字符串数组长度: ");
int n = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
String[] arr = new String[n];
System.out.println("输入字符串数组元素: ");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextLine();
}
System.out.println("输入的字符串数组: ");
for (String str : arr) {
System.out.println(str);
}
scanner.close();
}
}
从文件输入数组
如果需要从文件中读取数组,可以使用Scanner或BufferedReader读取文件内容。
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner fileScanner = new Scanner(new File("input.txt"));
int n = fileScanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = fileScanner.nextInt();
}
System.out.println("从文件输入的数组: ");
for (int num : arr) {
System.out.print(num + " ");
}
fileScanner.close();
}
}
注意事项
- 输入时需要确保数据类型匹配,避免因类型不匹配导致的异常。
- 使用
Scanner时,注意处理换行符(如调用nextLine()前调用nextInt()会留下换行符)。 - 对于大量数据输入,
BufferedReader比Scanner更高效。







