SlothMan
SlothMan

Reputation: 21

How to find the largest number in the array

I have an array of grades(g) which is an int[] and I'm trying to find the largest grade in that array. I have tried this:

public static String highestGradeName(int[] g, String[] n) {
    String highStudent;
    int highest = g[0];
    for (int i=1; i < g.length; i++) {
        if (highest < g[i]) {
            highStudent = n[i+1];
            return (highStudent);
        }
    }
    return null;
}

I have another array which is a String array and contains the names of the students, I have the return null there because it said it needed a return statement however I didn't plan on it ever being null. What's causing it to return null instead of highstudent?
I've used the exact code to find the lowest grade and it works fine the only thing I did to this one was change the if statement from highest > g[i] to highest < g[i].

Upvotes: 1

Views: 88

Answers (2)

Ashish Yadav
Ashish Yadav

Reputation: 2028

According to your logic let's break things.

Raw Test Case:

Take {0,1,2} as an integer arrays. Take {"arya", "jon", "tyrion"} as an string arrays.

highest = 0; // according to your code.

For int i = 1, i < 3; i++
0 < 1
highstudent = 2 // tyrion
// returns tyrion

The reason why you are getting null is your integer at 0 index should be greater or equal to the index at 1.

Now, when you are using a type String in your method. You should return a string and that's what your editor said to have something return. You should use return out of the loop because you need to find the highest student which is only possible after looping all the list.

You can try this:

public static String highestGradeName(int[] g, String[] n) {

    int max = 0; 
    int index = 0;
    for (int i = 0; i < g.length; i++) {
        if (max < g[i]) {
            max = g[i];
            index = i;
        }
    }
    return n[index];

}

PS: Imporve code according to mureinik answer, I have one more variable to help you understand easily.

Upvotes: 0

Mureinik
Mureinik

Reputation: 312219

Returning from inside the loop is wrong, as you can always have an even larger number later on in the array. You should keep the index of the highest grade and just return the corresponding name at the end:

public static String highestGradeName(int[] g, String[] n) {
    int highest = 0;
    for (int i = 1; i < g.length; i++) {
        if (g[highest] < g[i]) {
            highest = i;
        }
    }
    return n[highest];
}

Upvotes: 3

Related Questions