Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

Entering array in 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));
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're supposed to run this code through the command line. Example:

java ClassName 0 4 7 12 55

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.

Note: there are some IDEs that handle command line arguments for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...