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
206 views
in Technique[技术] by (71.8m points)

java - Finding a minimum and maximum value in an array

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

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

1 Reply

0 votes
by (71.8m points)

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


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

...