user5644453
user5644453

Reputation:

How do I select the max value from an array?

I'm creating a elementary math tutorial, and for this portion I have an array, the array is filled with 5 random numbers, between 0 and 9. The question I am creating would give 5 random digits, and say "What is the highest number that you could make with these digits?", and then I store that number in a variable

    // These are all Random numbers using the Random method
    a = num.nextInt(9);
    b = num.nextInt(9);
    c = num.nextInt(9);
    d = num.nextInt(9);
    e = num.nextInt(9);
    f = num.nextInt(9);

    // Asks the question right here (not important right now)
    // prints out 5 digits here (again, not important right now)

    g = ans.nextInt(); // this is the users response 

    int h3[] = {a, b, c, d, e, f}; // this array holds the random numbers

Upvotes: 0

Views: 325

Answers (5)

MC Emperor
MC Emperor

Reputation: 23047

The problem with the currently accepted answer is that it sorts the array. This may impact performance if the array of ints is very large. The array doesn't have to be sorted.

Just iterate over the array and store the highest number:

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

Or store the index of the highest number instead:

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

You could also use Java Streams:

return IntStream.of(array).max().getAsInt();

Of course, all of these snippets assume that the array contains at least one element.

Upvotes: 0

user4910279
user4910279

Reputation:

In java8

 IntStream.of(h3).max().getAsInt();

Upvotes: 2

Anton
Anton

Reputation: 420

    Arrays.sort(h3);
    int maxNo = h3[h3.length-1].

This should do what you require. Your highest value will be set to maxNo. Dont forget to import Java.util.*;

Upvotes: -1

Zachery
Zachery

Reputation: 111

The best way I could think of doing this would be to make an int variable and loop through the array, and if the number is bigger than what is in the int variable, overwrite it.

int biggest = -1; //you want this to be negative one originally to ensure it is overwritten

for (int i = 0; i < num.length; i++) {
    if (num[i] > biggest) {
        biggest = num[i];
    }
}

Upvotes: 0

Naruto
Naruto

Reputation: 4329

Sort the array in descending order. The number would be the highest 5 digit number.

Although you asked for 5 random numbers but you are filling with six random numbers. Please correct that also.

int h3[] = {a, b, c, d, e, f};

Upvotes: 0

Related Questions