如何获取数组中最大值的索引?

时间:2017-05-02 01:15:57

标签: java arrays

我有两个数组

String[] city;
int[] temp;

它们的长度均为4.城市拥有每个城市的名称,而温度保持每个城市的平均温度。临时温度与城市中的城市顺序相同。所以我的问题是,如何获得temp中max int的索引?我想打印出来

"The city with the highest average temperature is " + city[index] + 
" with an average temperature of " + temp[max];

我想在城市中获取max int的索引,然后将其插入city []。由于数组大小相同且顺序相同,我只需要能够在int [] temp中返回最大值的索引;

4 个答案:

答案 0 :(得分:3)

如果您不想使用其他课程,可以执行以下操作。 您需要存储max的最大值和索引,以便您还可以打印城市

String[] city = getCities ();  // assuming this code is done
int[] temp = getTemparatures ();
int max = Integer.MIN_VALUE;
int index = -1;

for(int i = 0; i < temp.length; i ++){
    if(max < temp[i]){
        max = temp[i];
        index = i;
    }
}

System.out.println ("The city with the highest average temperature is " + city[index] + 
" with an average temperature of " + temp[index]);

答案 1 :(得分:-1)

您可以使用<name>.length获取数组的长度。数组的长度比最高索引多一个,所以你应该使用&#39; name [ name .length - 1]`获得最高的项目索引。

答案 2 :(得分:-2)

抱歉,我在这个编辑器中写道,但实质是相同的

int max = -100;
for (int i = 0; i < temp.length; i++){
    if (temp[i] > max){
        max = temp[i];
    }
}
System.out.print("The city with the highest average temperature is " + city[your index] + 
" with an average temperature of " + max);

答案 3 :(得分:-2)

您可以遍历temp数组,找到max并将值存储为变量,并在输出语句中使用该变量。下面是一些代码,希望这有帮助

String[] city;
int[] temp;
int max = 0;

for(int i = 0; i < temp.size; i ++){
    if(max < temp[i]){
        max = temp[i];
    }
}

"The city with the highest average temperature is " + city[max] + 
" with an average temperature of " + temp[max];