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

So I'm trying to find a min and max of an array which are put in by the user.

This is my code

public static void main(String[] args) {

    int[] a = new int[args.length];
    for (int i = 0; i < args.length; i++) {
        a[i] = Integer.parseInt(args[i]);
        int max = a[0];
        for (int j = 1; j < args.length; j++) {
            if (a[j] > max) {
                max = a[j];
            }
        } 
        System.out.println("the maximum value of the array is " + max);
    }
}

But the output I am getting is every single number I have put in. What is my mistake here?

See Question&Answers more detail:os

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

1 Answer

Let's go through the process. Because this is an int array the values are initialized to 0. In the first for loop we assign the first int to a[0]. Then in the second for loop we check every value in the array if it is maximal (so checking the first value against a load of zeros) then you exit the nested for loop and print the statement (with the value of a[0], if it was positive).

Now we go through the second cycle of the outer loop, if this was bigger again this value will be printed, otherwise the first value will be reprinted (was your array in ascending order by any chance?) and so on for each value.

As was commented, a single loop would be enough, and ensure your print statement is outside of the outer for loop

Hope this helps


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