Java中数组获取最大值

最大值获取:从数组的所有元素中找出最大值。

实现思路:
定义变量,保存数组0索引上的元素
遍历数组,获取出数组中的每个元素
将遍历到的元素和保存数组0索引上值的变量进行比较
如果数组元素的值大于了变量的值,变量记录住新的值
数组循环遍历结束,变量保存的就是数组中的最大

//求最大值
public class ArrayDemo3 {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,6};//定义一个数组存放指定元素

        int sum = arr[0];//假设第一个元素是最大值
        //for循环遍历数组中元素,每次循环跟数组索引为0的元素比较大小
        for (int i = 0; i < arr.length; i++){
            if (sum < arr[i]){//数组中的元素跟sum比较,比sum大就把它赋值给sum作为新的比较值
                sum = arr[i];
            }
        }
        System.out.println(sum);//输出数组中的最大值
    }
}

猜你喜欢

转载自www.cnblogs.com/libinhong/p/10988781.html