【问题标题】:how can I get the index of the max value in an array?如何获取数组中最大值的索引?
【发布时间】:2017-05-02 01:15:56
【问题描述】:

我有两个数组

String[] city;
int[] temp;

它们的长度都是 4。city 保存了每个城市的名称,temp 保存了每个城市的平均温度。 temp 中的温度与 city 中的城市的顺序相同。所以我的问题是,我怎样才能在 temp 中获得最大 int 的索引?我要打印出来

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

我想到了获取 city 中最大 int 的索引,并将其插入 city[]。由于数组的大小和顺序相同,我只需要能够返回 int[] temp 中的最大值的索引;

【问题讨论】:

  • 如果你想知道最大值的索引,你可以遍历数组找到最大值并记住索引。或使用@Alex 的建议来使用 NumberUtils。旁注,设计问题:呃......你为什么不把临时和城市“绑定”在一起成为一个类......?像city 类。那么该类包含城市名称和温度..?
  • 这似乎是同一个问题stackoverflow.com/questions/43728432/…
  • @ScaryWombat 我不能对这个问题发表评论,因为我是新手,但我有一个问题要问。您能否通过创建一个包含整数和字符串的对象来扩展您的意思?
  • public class CityTemp { String city; int temp} CityTemp [] = new CityTemp [201]; 这很粗糙

标签: java arrays


【解决方案1】:

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

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]);

【讨论】:

  • 非常感谢!你是救生员。
【解决方案2】:

您可以使用&lt;name&gt;.length 获取数组的长度。数组的长度比最高索引大一,因此您应该使用 'name[name.length - 1]` 来获取具有最高索引的项目。

【讨论】:

  • 问题是关于数组中的最大值,而不是数组本身的长度。
【解决方案3】:

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

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];

【讨论】:

  • temp.size????而这是如何获取温度最高的数组元素的索引呢?
【解决方案4】:

对不起,我在这个编辑器里写过,但是本质是一样的

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);

【讨论】:

  • 好的...所需的索引值在哪里。
  • 我希望他自己想出来。还不是一个准备好的决定……
猜你喜欢
  • 2018-12-09
  • 1970-01-01
  • 1970-01-01
  • 2019-09-11
  • 2021-07-19
  • 2011-10-18
  • 1970-01-01
  • 2022-08-16
相关资源
最近更新 更多