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

使用Java函数编写一个程序来查找一个数组中的最大值。

发布时间:2023-07-03 11:03:32

下面是一个使用Java函数编写的程序来查找一个数组中的最大值:

public class FindMaxValue {
    
    public static void main(String[] args) {
        int[] arr = {5, 3, 9, 1, 7};
        int maxValue = findMaxValue(arr);
        System.out.println("The maximum value in the array is: " + maxValue);
    }
    
    public static int findMaxValue(int[] arr) {
        if (arr == null || arr.length == 0) {
            throw new IllegalArgumentException("Array cannot be null or empty.");
        }
        
        int max = arr[0];
        
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        
        return max;
    }
}

这个程序接受一个整数数组作为输入,并使用findMaxValue函数来查找最大值。

findMaxValue函数首先对输入进行验证,如果数组为空或长度为0,则抛出IllegalArgumentException异常。

然后,它使用一个循环来遍历数组中的元素。在每次迭代中,它比较当前元素与最大值,并在找到更大的元素时更新最大值。最后,返回最大值。

在上面的例子中,数组arr的最大值为9,因此程序的输出应为"The maximum value in the array is: 9"。