Java求最大值的四种方法

/**
*@author Prannt
*求最大值(或最小值)
*本例以int数据类型为例,可指定其他数据类型
*/

//方法一:直接法,求最小值类似
public class Deno05ArrayMax {
    public static void main(String[] args) {
    	//数据类型可指定
        int [] array = {5,15,20,30,10000};
        int max = array[0];//假设第一个值为最大值
        for (int i = 1; i < array.length; i++) { //和后面的数进行比较
            if(array[i] > max) {
                max = array[i];
            }
        }
        System.out.println("最大值是:" + max);
    }
}


//方法二:调用方法求最大值,求最小值类似
public class Demo02Method {

    public static void main(String[] args) {
        int [] array = {5,15,35}; 
        int max = getMax(array);
        System.out.println("最大值:" + max);
    }	
	//有返回值,含参
    public static int getMax (int [] array) {
        int max = array[0];  //局部变量写在方法内部
        for (int i = 1; i < array.length; i++) {
            if (array[i] > max ) {
                max = array[i];
            }
        }
        return max;
    }
}

//方法三:三元运算符,求最小值类似
public class Demo02Method {
    public static void main(String[] args) {
        int[] arr = {5, 2, 3, 12,10,11,17,1,-1,-8};
        int result = arr[0];
        for (int i = 1; i < arr.length; i++){
            // ? 前面的表达式为条件判断
            //逻辑为:如果条件表达式成立则执行result,否则执行arr[i]
            result = (arr[i] < result ? result : arr[i]);
        }
        System.out.println("最大值为:" + result);
    }
}

//方法四:面向对象调用,求最小值类似
public class Demo02Method {
    int [] arr = {9,20,5,6,1,3,7,2,4};
    int num = arr[0];
    public static void main(String args[]) {
        Demo02Method max=new Demo02Method();
        //调用方法
        max.getMax();
    }

    public void getMax() {
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] > arr[0]) {
                num = arr[i];
            }
        }
        System.out.println("最大值为:" + num);
    }
}



  • 23
    点赞
  • 102
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值