声明整数值数组m
并创建它(分配内存)。数组的大小应由程序执行期间命令行中提供的参数定义。
public class A {
public static void main(String[] args) {
int[] a;
int[] b = new int[n];
for (int i = 0; i < n; i++) {
b[i] = a[i];
}
}
}
这是我的代码,但我认为它不正确。我应该在代码中使用变量 args 吗?请向我解释更多有关内存分配的信息。谢谢。
最佳答案
1) 你需要初始化a[]
2) 使用 String[] args
检索命令行参数(并且需要将其解析为 Integer )
尝试这样。
class A {
public static void main(String[] args) {
try {
String nn = args[0];
int n = Integer.parseInt(nn);
int[] a = new int[n];
for (int i = 0; i < n; i++) {
// your implementation goes here
}
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Please specify a argument");
}
catch (NumberFormatException e) {
System.out.println("Argument must be a integer value");
}
}
}
关于java - 打印应在命令行中提供大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48762619/