简体   繁体   中英

How do I find the maximum number in an array in Java

I am given the array measurements[]. I am supposed to write a for loop that goes through all the numbers and each time a number maximum is reached, the variable maximum is replaced. In the code I have so far, the output is saying that it cannot find the symbol i, but I thought that was the symbol I am supposed to use within a for-loop. Here is my code:

    double maximum = measurements[0];
    for (i = 0; i < measurements.length; i++) {
        if (array[i] > largest) {
            largest = array[i];
    }
    }
System.out.println(maximum);

You can also do this using Java stream api :

double maximum = Arrays.stream(measurements).max();
System.out.println(maximum);

Or a more concise code:

double maximum = Double.MIN_VALUE;
for(double measurement : measurements) {
    maximum = Math.max(maximum, measurement);
}
System.out.println(maximum);

Or, sort the array and return the last one

Arrays.sort(measurements);
System.out.println(measurements[measurements.length-1]);

you can try this -

class MaxNumber
{
    public static void main(String args[])
    {
        int[] a = new int[] { 10, 3, 50, 14, 7, 90};
        int max = a[0];
        for(int i = 1; i < a.length;i++)
        {
            if(a[i] > max)
            {
                max = a[i];
            }
        }

        System.out.println("Given Array is:");
        for(int i = 0; i < a.length;i++)
        {
            System.out.println(a[i]);
        }

        System.out.println("Max Number is:" + max);
    }
}

You have not declared i inside the for loop or before the for loop.

double maximum = measurements[0];
    for (int i = 0; i < measurements.length; i++) {  //You can declare i here.
        if (array[i] > largest) {
            largest = array[i];
    }
    }
System.out.println(maximum);

You can also declare i before the for loop also

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