Java中求最大值的4种方法实例代码

前言

本文主要给大家分享了关于java求最大值的4中方法,文中给出了完整的示例代码,下面话不多少了,来一起看看吧

示例代码:

/**
*@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);
 }
}

总结