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

时间:2013-11-19 01:08:02

标签: 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];
            }
        }

2 个答案:

答案 0 :(得分:0)

public static void findHottest(int[] temp){
    int hottest = temp[0];
    int highestIndex = 0;

    for(int i = 1; i < temp.length; i++){
        if(temp[i] > hottest) {
            hottest = temp[i];
            highestIndex = i;
    }
}

只要在遇到更高的值时存储索引。

答案 1 :(得分:0)

你已经有了答案。在你的代码中

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

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