Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...