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