Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何找到数组中的最高值及其位置_Java_Arrays - Fatal编程技术网

Java 如何找到数组中的最高值及其位置

Java 如何找到数组中的最高值及其位置,java,arrays,Java,Arrays,所以我有一个数组,我知道如何找到最高值,但我不知道如何获得该值在数组中的位置。目前的方法如下: public static void findHottest(int[] temp){ int hottest = temp[0]; for(int i = 1; i < temp.length; i++){ if(temp[i] > hottest) { hottest = temp[i];

所以我有一个数组,我知道如何找到最高值,但我不知道如何获得该值在数组中的位置。目前的方法如下:

 public static void findHottest(int[] temp){
        int hottest = temp[0];
        for(int i = 1; i < temp.length; i++){
            if(temp[i] > hottest) {
                hottest = temp[i];
            }
        }
publicstaticvoidfindhottest(int[]temp){
int=temp[0];
对于(int i=1;i最热){
最热=温度[i];
}
}
公共静态void findHottest(int[]temp){
int=temp[0];
int highestIndex=0;
对于(int i=1;i最热){
最热=温度[i];
高指数=i;
}
}

当您遇到更高的值时,只需存储索引。

您已经在代码中找到了答案

    public static void findHottest(int[] temp){
            int hottest = temp[0];
int index =0;
            for(int i = 1; i < temp.length; i++){
                if(temp[i] > hottest) {
                    hottest = temp[i]; 
                    index =i // index is the index you are looking for.
                }
            }
publicstaticvoidfindhottest(int[]temp){
int=temp[0];
int指数=0;
对于(int i=1;i最热){
最热=温度[i];
index=i//index是您要查找的索引。
}
}

因此,只要有一个
index
变量,只要执行
horst=temp[i]
语句,该变量就会更新。

So。您所需要做的就是添加一个“position”变量,跟踪“horst”条目的索引。
    public static void findHottest(int[] temp){
            int hottest = temp[0];
int index =0;
            for(int i = 1; i < temp.length; i++){
                if(temp[i] > hottest) {
                    hottest = temp[i]; 
                    index =i // index is the index you are looking for.
                }
            }