在Java中输入数组 [英] Entering array in java
问题描述
我找到了这段代码,该代码读取一些数字作为参数,然后将它们分配为数组中的值.我不明白java如何知道数组长度应该是多少?
I found this code, which reads some numbers as arguments and then assigns them as values in an array. I can't understand how java knows what the array length should be ?
public static void main(String[] args) {
int n = args.length;
int[] dataset = new int[n];
for (int i = 0; i < n; i++) {
dataset[i] = Integer.parseInt(args[i]);
}
System.out.println(java.util.Arrays.toString(dataset));
}
推荐答案
您应该通过命令行运行此代码.示例:
You're supposed to run this code through the command line. Example:
java ClassName 0 4 7 12 55
Java将知道长度,因为它具有输入值数组: 0 4 7 12 55
.此数组与传递给 main
方法的 String [] args
相同.
Java will know the length because it has an array of input values: 0 4 7 12 55
. This array is the same as String[] args
passed into the main
method.
If you want to learn more about command line arguments, then I'd recommend this source.
注意:有些IDE可以为您处理命令行参数.
Note: there are some IDEs that handle command line arguments for you.
这篇关于在Java中输入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!