在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个素到数组中。
请根据你的需求选择合适的方法,并尝试运行代码
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/67976.html