在Java中,你可以使用`Scanner`类从键盘输入数组元素。以下是一个简单的示例代码,展示了如何实现这一功能:
import java.util.Scanner;
public class ArrayInput {
public static void main(String[] args) {
// 创建一个 Scanner 对象来读取输入
Scanner scanner = new Scanner(System.in);
// 提示用户输入数组的大小
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt(); // 读取数组的大小
// 创建一个大小为 size 的整型数组
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("The input array is:");
for (int i = 0; i < size; i++) {
System.out.print(array[i] + " ");
}
// 关闭 Scanner 对象
scanner.close();
}
}
当你运行这个程序时,它会提示你输入数组的大小,然后逐个输入数组的元素。输入完成后,程序会输出你输入的数组内容。
如果你需要限制输入的数组个数,可以稍微修改代码,比如指定一个固定的数组长度,如下所示:
import java.util.Scanner;
public class ArrayInput {
public static void main(String[] args) {
// 创建一个 Scanner 对象来读取输入
Scanner scanner = new Scanner(System.in);
// 指定数组长度
int size = 3;
int[] array = new int[size];
// 提示用户输入数组的元素
System.out.println("Enter " + size + " elements of the array:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt(); // 读取数组的每个元素
}
// 输出输入的数组
System.out.println("The input array is:");
for (int i = 0; i < size; i++) {
System.out.print(array[i] + " ");
}
// 关闭 Scanner 对象
scanner.close();
}
}
这个版本的程序会限制用户只能输入3个元素到数组中。