java录入任意个数在数组中
可以使用Scanner类来实现从键盘输入任意个数,并将其存储到数组中。以下是示例代码:
import java.util.Scanner;
public class InputArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入数组大小:");
int n = scanner.nextInt(); // 输入数组大小
int[] arr = new int[n]; // 创建大小为n的数组
System.out.println("请输入" + n + "个整数:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt(); // 逐个输入数组元素
}
System.out.println("输入的数组为:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " "); // 输出数组元素
}
}
}
运行该程序,输入数组大小和数组元素即可。例如,输入大小为5,元素为1、2、3、4、5的数组,输出结果如下:
请输入数组大小:5
请输入5个整数:
1
2
3
4
5
输入的数组为:
1 2 3 4 5
``
原文地址: https://www.cveoy.top/t/topic/eC8j 著作权归作者所有。请勿转载和采集!