简体   繁体   English

如何在Java中找到数组中的最大数字

[英]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.我应该编写一个遍历所有数字的 for 循环,每次达到数字最大值时,变量最大值被替换。 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.在我到目前为止的代码中,输出说它找不到符号 i,但我认为这是我应该在 for 循环中使用的符号。 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 :您也可以使用 Java 流 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.您尚未在 for 循环内或 for 循环之前声明i

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您也可以在 for 循环之前声明 i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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