欢迎访问宙启技术站
智能推送

在Java中编写函数,以整数形式返回数组中最大元素的索引

发布时间:2023-06-30 04:42:16

以下是Java中编写的函数,用于返回数组中最大元素的索引:

public class Main {
    public static void main(String[] args) {
        int[] numbers = {5, 3, 9, 10, 7};
        int maxIndex = findMaxIndex(numbers);
        System.out.println("最大元素的索引是:" + maxIndex);
    }

    public static int findMaxIndex(int[] array) {
        if (array == null || array.length == 0) {
            throw new IllegalArgumentException("数组不能为空");
        }

        int maxIndex = 0;
        int maxValue = array[0];

        for (int i = 1; i < array.length; i++) {
            if (array[i] > maxValue) {
                maxValue = array[i];
                maxIndex = i;
            }
        }

        return maxIndex;
    }
}

在上述代码中,首先定义了一个main函数来测试findMaxIndex函数。在main函数中,创建了一个整数数组numbers,并将它传递给findMaxIndex函数。然后,将返回的最大元素的索引打印出来。

findMaxIndex函数的参数是一个整数数组array。该函数首先会检查数组是否为空或长度为0,如果是,则抛出一个IllegalArgumentException。接下来,在一个循环中遍历数组的元素,如果当前元素的值大于最大值maxValue,则更新最大值和最大索引maxIndex。最后,返回最大索引。

在上述代码的示例中,数组numbers的最大元素是10,它的索引是3。因此,在控制台上的输出将是:"最大元素的索引是:3"。