args.length和命令行参数 [英] args.length and command line arguments
问题描述
我对如何使用args.length感到困惑,我在这里编写了一些代码:
I got confused with how to use args.length, I have coded something here:
public static void main(String[] args) {
int [] a = new int[args.length];
for(int i = 0;i<args.length;i++) {
System.out.print(a[i]);
}
}
无论我输入什么价值,打印输出为0命令行参数,我想我可能把args.length与args [0]混淆了,有人可以解释一下吗?谢谢。
The printout is 0 no matter what value I put in command line arguments, I think I probably confused args.length with the args[0], could someone explain? Thank you.
推荐答案
int
数组初始化为零(所有成员)将默认为零,参见 4.12.5。变量的初始值:
int
array is initialized to zero (all members will be zero) by default, see 4.12.5. Initial Values of Variables:
每个类变量,实例变量或数组组件都使用默认值初始化创建
...
Each class variable, instance variable, or array component is initialized with a default value when it is created ...
对于int类型,默认值为零。
您正在打印数组的值,因此您得到 0
。
You're printing the value of the array, hence you're getting 0
.
您是否尝试过这样做?
for (int i = 0; i < args.length; i++) {
System.out.print(args[i]);
}
args
包含传递给程序的命令行参数。
args.length
是参数的长度。例如,如果你运行:
args
contains the command line arguments that are passed to the program. args.length
is the length of the arguments. For example if you run:
java myJavaProgram first second
args.length
将为2,它将包含 [first,second ]
。
并且数组args的长度自动设置为2(参数个数),因此不需要设置args的长度。
And the length of the array args is automatically set to 2 (number of your parameters), so there is no need to set the length of args.
这篇关于args.length和命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!