简体   繁体   中英

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

在java8中

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

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};

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];
    }
}
    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.*;

The accepted answer indeed works, but is bad for performance.

Just iterate over the array and store the highest number:

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

One could indeed sort the array and then pick the last array element:

Arrays.sort(array);
int max = array[array.length - 1];

This would do the trick, but one should know that this results in bad performance .

Also note that the Java 8 method below seems to be very slow in this case. Maybe it will get relatively faster when the array becomes larger.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM