gpt4 book ai didi

java - 显示索引数组

转载 作者:行者123 更新时间:2023-12-02 00:06:52 25 4
gpt4 key购买 nike

我有一个问题。我正在尝试显示数组中最大值的索引。我能够获得最大值;但是,我不知道如何显示该最大值的索引。

例如,如果索引 [3] 的值为 5 并且是数组中最大的元素,则会打印:

value[3] = 5 是最大元素

我该怎么做?

    import java.util.Scanner;

public class ArrayExample
{
public static void main(String[] args)
{
//Question 1
int values[] = new int[5] ;
System.out.println("Please enter 5 values for this array: ");
Scanner keyboard = new Scanner(System.in);


System.out.println("Maximum Value = " + getMaxIndex(values) + getMaxValue(values));
}

public static int getMaxValue(int[] values){
int maxValue = values[0];
for(int i=0;i<values.length;i++){
if(values[i] > maxValue){
maxValue = values[i];
}
}
return maxValue;
}
public static int getHighestMonth(int[] values) {
int highest = 0;
for (int i = 0; i < 5; i++) {
if (values[i] > values[highest]) {
highest = i;
}
}
return highest;
}

}

最佳答案

您可以使用AbstractMap.SimpleEntry:

public static SimpleEntry<Integer, Integer> getMaxValue(int[] values){  
int maxValue = Integer.MIN_VALUE;
int maxIndex = -1;
for(int i=0;i<values.length;i++){
if(values[i] >= maxValue){
maxValue = values[i];
maxIndex = i;
}
}
return new SimpleEntry<Integer, Integer>( maxIndex, maxValue);
}

public static void main(String[] args) {
SimpleEntry<Integer, Integer> maxEntry = getMaxValue( new int[]{1,2,3});

System.out.println( "value["+ maxEntry.getKey() + "] = " + maxEntry.getValue() + " is the largest element");
//value[2] = 3 is the largest element

}

关于java - 显示索引数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13671586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com