Nina Hain
Nina Hain

Reputation: 41

Returning max value in java

Pretty simple question I'm sure, since I'm only just learning.

In a larger class that I am on my way of implementing, we have to provide a method Max to return the maximum value in an array. This is what I have:

public static int Max(int[] window){
    //assume length of array window > 0

    int Max = window[0];
    for (int i = 1; i < window.length; i++){
        if (window[i] > Max) {
            Max = window[i];
        }
        return Max;
    }
}

However, the method does not compile. I believe it has something to do with the return type. The program calls up this function (and a similar Min function) like this further on in the program:

System.out.println("[" + window.Min() + " " + window.Max() + "]");

What am I doing wrong?

EDIT: Thanks for all of your answers! Just started learning coding, so trivial mistakes like this one can still cause a whole lot of frustration. Saving my ass, all of you!

Upvotes: 0

Views: 4130

Answers (3)

Paul Boddington
Paul Boddington

Reputation: 37655

The return statement should not be in the for loop.

It should be

 public static int Max(int[] window){
    //assume length of array window > 0

    int Max = window[0];
    for (int i = 1; i < window.length; i++){
        if (window[i] > Max) {
            Max = window[i];
        }
    }
    return Max;
}

It doesn't compile because it is possible to get to the end of the method without anything being returned. If the length of the array is 0 or 1 the loop will not be entered and the return not executed.

Upvotes: 2

rgettman
rgettman

Reputation: 178303

Java always considers the possibility of the for loop not being entered, and sees no return statement at the end of the method, giving a missing return statement compiler error. The method is declared to return something, an int, so every possible execution path must return something.

Move return Max; after the end of the for loop, both to satisfy the compiler and to provide a correct "find the max" method.

Incidentally, Java variables usually have a lowercase first letter per normal conventions. The Max variable should be called max. The same applies to the name of the Max method.

Upvotes: 3

Daniel Kaplan
Daniel Kaplan

Reputation: 67440

I believe this does not compile because there's a way you can get to the end of the method without an explicit return statement.

You need to put that return Max; at the bottom, as opposed to inside the for loop:

public static int Max(int[] window){
    //assume length of array window > 0

    int Max = window[0];
    for (int i = 1; i < window.length; i++){
        if (window[i] > Max) {
            Max = window[i];
        }

    }
    return Max;
}

Upvotes: 2

Related Questions