如何在 Java 中定义数组大小且不进行硬编码?
为了避免硬编码,你可以使用读取器类的命令行参数,例如 Scanner 从用户那里读取数组的大小。然后使用这个值创建数组。
示例
import java.util.Arrays;
import java.util.Scanner;
public class PopulatingAnArray {
public static void main(String args[]) {
System.out.println("Enter the required size of the array :: ");
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int myArray[] = new int [size];
System.out.println("Enter the elements of the array one by one ");
for(int i=0; i<size; i++) {
myArray[i] = s.nextInt();
}
System.out.println("Contents of the array are: "+Arrays.toString(myArray));
}
}输出
Enter the required size of the array :: 5 Enter the elements of the array one by one 78 96 45 23 45 Contents of the array are: [78, 96, 45, 23, 45]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP