Java:查找数组中的最大值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1806816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:51:11  来源:igfitidea点击:

Java: Finding the highest value in an array

javaarraysmax

提问by HelloWorld

For some reason this code is printing three values for the highest value in the array when I'm trying to print just one (which is 11.3). Can someone please explain to me why it is doing this?

出于某种原因,当我尝试仅打印一个值(即 11.3)时,此代码为数组中的最高值打印了三个值。有人可以向我解释为什么这样做吗?

Thanks.

谢谢。

import java.util.Scanner;

public class Slide24
{
    public static void main (String [] args)
    {
        Scanner in = new Scanner(System.in);

        double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4,
            8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2,
            3.5, 3, 1.1, 6.5, 5.1, -1.2, -5.1, 2, 5.2, 2.1};

        double total = 0, avgMax = 0;

        for (int counter = 0; counter < decMax.length; counter++)
        {
         total += decMax[counter];
        }

        avgMax = total / decMax.length;

        System.out.printf("%s %2.2f\n", "The average maximum temperature for December was: ", avgMax);

        //finds the highest value
        double max = decMax[0];

        for (int counter = 1; counter < decMax.length; counter++)
        {
         if (decMax[counter] > max)
         {
          max = decMax[counter];
          System.out.println("The highest maximum for the December is: " + max);
         }

        }        
    }
}

采纳答案by Toji

It's printing out a number every time it finds one that is higher than the current max (which happens to occur three times in your case.) Move the print outside of the for loop and you should be good.

每次它发现一个高于当前最大值的数字时,它都会打印出一个数字(在您的情况下恰好发生了 3 次。)将打印移到 for 循环之外,您应该会很好。

for (int counter = 1; counter < decMax.length; counter++)
{
     if (decMax[counter] > max)
     {
      max = decMax[counter];
     }
}

System.out.println("The highest maximum for the December is: " + max);

回答by Michael Haren

You need to print out the max afteryou've scanned all of them:

扫描完所有这些后,您需要打印出最大值:

for (int counter = 1; counter < decMax.length; counter++)
{
    if (decMax[counter] > max)
    {
        max = decMax[counter];
        // not here: System.out.println("The highest maximum for the December is: " + max);
    }
}  
System.out.println("The highest maximum for the December is: " + max);

回答by twolfe18

You have your print()statement in the for()loop, It should be after so that it only prints once. the way it currently is, every time the max changes it prints a max.

你在循环中有你的print()语句for(),它应该在之后,以便它只打印一次。目前的方式是,每次 max 更改时,它都会打印一个max.

回答by sifho

To find the highest (max) or lowest (min) value from an array, this could give you the right direction. Here is an example code for getting the highest value from a primitive array.

要从数组中找到最高 (max) 或最低 (min) 值,这可以为您提供正确的方向。这是从原始数组中获取最高值的示例代码。

Method 1:

方法一:

public int maxValue(int array[]){
  List<Integer> list = new ArrayList<Integer>();
  for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
  }
 return Collections.max(list);

}

}

To get the lowest value, you can use

要获得最低值,您可以使用

Collections.min(list)

Method 2:

方法二:

public int maxValue(int array[]){
  int max = Arrays.stream(array).max().getAsInt();
  return max;
}

Now the following line should work.

现在以下行应该可以工作。

System.out.println("The highest maximum for the December is: " + maxValue(decMax)); 

回答by christylam1

If you are looking for the quickest and simplest way to perform various actions in regards to arrays, the use of the Collections class is extremely helpful (documentation available from https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html), actions ranges from finding the maximum, minimum, sorting, reverse order, etc.

如果您正在寻找对数组执行各种操作的最快捷、最简单的方法,则使用 Collections 类非常有用(文档可从https://docs.oracle.com/javase/7/docs/api/ java/util/Collections.html),操作范围从查找最大值、最小值、排序、倒序等。

A simple way to find the maximum value from the array with the use of Collections:

使用集合从数组中查找最大值的简单方法:

Double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4, 8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2, 3.5, 3.0, 1.1, 6.5, 5.1, -1.2, -5.1, 2.0, 5.2, 2.1};
List<Double> a = new ArrayList<Double>(Arrays.asList(decMax));
System.out.println("The highest maximum for the December is: " + Collections.max(a));

If you are interested in finding the minimum value, similar to finding maximum:

如果您对查找最小值感兴趣,类似于查找最大值:

System.out.println(Collections.min(a));

The simplest line to sort the list:

对列表进行排序的最简单行:

Collections.sort(a);

Or alternatively the use of the Arrays class to sort an array:

或者使用 Arrays 类对数组进行排序:

Arrays.sort(decMax);

However the Arrays class does not have a method that refers to the maximum value directly, sorting it and referring to the last index is the maximum value, however keep in mind sorting by the above 2 methods has a complexity of O(n log n).

但是 Arrays 类没有直接引用最大值的方法,对其进行排序并引用最后一个索引是最大值,但是请记住,通过上述 2 种方法进行排序的复杂度为 O(n log n) .

回答by Sahil Chhabra

Same as suggested by others, just mentioning the cleaner way of doing it:

与其他人的建议相同,只是提到了更清洁的方法:

int max = decMax[0];
for(int i=1;i<decMax.length;i++)
    max = Math.max(decMax[i],max);
System.out.println("The Maximum value is : " + max);

回答by freedev

A shorter solution to have the max value of array:

具有数组最大值的较短解决方案:

double max = Arrays.stream(decMax).max(Double::compareTo).get();

回答by Shimrod

You can use a function that accepts a array and finds the max value in it. i made it generic so it could also accept other data types

您可以使用接受数组并在其中查找最大值的函数。我使它通用,因此它也可以接受其他数据类型

public static <T extends Comparable<T>> T findMax(T[] array){       
    T max = array[0];
    for(T data: array){
        if(data.compareTo(max)>0)
            max =data;                
    }
    return max;
}

回答by Vivek Shah

You can write like this.

你可以这样写。

import java.util.Scanner;
class   BigNoArray{

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter how many array element");
        int n=sc.nextInt();
        int[] ar= new int[n];
        System.out.println("enter "+n+" values");
        for(int i=0;i<ar.length;i++){
            ar[i]=sc.nextInt();
        }
        int fbig=ar[0];
        int sbig=ar[1];
        int tbig=ar[3];
            for(int i=1;i<ar.length;i++){
                if(fbig<ar[i]){
                    sbig=fbig;
                    fbig=ar[i];
                }
                else if(sbig<ar[i]&&ar[i]!=fbig){
                    sbig=ar[i];
                }
                else if(tbig<ar[i]&&ar[i]!=fbig){
                    tbig=ar[i];
                }
            }
        System.out.println("first big number is "+fbig);
        System.out.println("second big number is "+sbig);
        System.out.println("third big number is "+tbig);
    }
}

回答by Ahmad Fayazi

void FindMax()
{
    int lessonNum;

    System.out.print("Enter your lesson numbers : ");
    lessonNum = input.nextInt();
    int[] numbers = new int[lessonNum];
    for (int i = 0; i < numbers.length; i++)
    {
        System.out.print("Please enter " + (i + 1) + " number : ");
        numbers[i] = input.nextInt();
    }
    double max = numbers[0];
    for (int i = 1; i < numbers.length; i++)
    {
        if (numbers[i] > max)
        {
            max = numbers[i];
        }
    }
    System.out.println("Maximum number is : " + max);
}