Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/332.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,我有两个数组 String[] city; int[] temp; 它们的长度都是4。City保存每个城市的名称,temp保存每个城市的平均温度。temp中的temp与city中的城市顺序相同。所以我的问题是,我怎样才能得到temp中max int的索引?我想打印出来 "The city with the highest average temperature is " + city[index] + " with an average temperature of " + temp[max

我有两个数组

String[] city;
int[] temp;
它们的长度都是4。City保存每个城市的名称,temp保存每个城市的平均温度。temp中的temp与city中的城市顺序相同。所以我的问题是,我怎样才能得到temp中max int的索引?我想打印出来

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

我想把城市中最大整数的索引插入城市[]。由于数组的大小和顺序相同,我只需要能够返回int[]temp中最大值的索引

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

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

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

您可以遍历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];

如果不想使用其他类,可以执行以下操作。 您需要同时存储max和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]);

如果你想知道最大值的索引,你可以遍历数组找到最大的索引并记住索引。或者使用@Alex的建议使用NumberRutils。旁注,设计问题:嗯。。。你为什么不把临时工和城市“绑定”成一个班。。?像城市班。然后这个类包含了城市名称和温度…?这似乎是同一个问题@ScaryWombat我不能评论这个问题,因为我是新来的,但我有一个问题要问。你可以通过创建一个包含int和String的对象来扩展你的意思吗?公共类CityTemp{String city;int temp}CityTemp[]=new CityTemp[201];这是非常非常粗糙的问题是关于数组中的最大值,而不是数组本身的长度。临时大小????那么这是如何获得最高温度的数组元素的索引的呢?好的……理想的索引值在哪里。我希望他能自己提出。不是一个准备好给予的决定…非常感谢!你是救命恩人。