java 定义一个方法找出一个整型数组中的最大值的下标注意最大值可能有多个 用布尔值
下面是一个Java方法的定义,用于找出一个整型数组中最大值的下标,并用布尔值表示最大值是否有多个。
public class Main {
public static void main(String[] args) {
int[] arr = {1, 5, 3, 9, 5, 7};
int maxIndex = findMaxIndex(arr);
System.out.println("最大值的下标为: " + maxIndex);
}
public static int findMaxIndex(int[] arr) {
int maxIndex = 0;
boolean multipleMax = false;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
multipleMax = false;
} else if (arr[i] == arr[maxIndex]) {
multipleMax = true;
}
}
if (multipleMax) {
System.out.println("最大值有多个");
}
return maxIndex;
}
}
运行结果为:
最大值的下标为: 3
``
原文地址: https://www.cveoy.top/t/topic/iwH4 著作权归作者所有。请勿转载和采集!