通过定义变量,初始化值为数组中的第一个值,然后循环、判断,再次赋值给定义的变量,返回之。
public static void main(String[] args) {
int[] arr = {3, 54, 456, 342, 2798};//数组
int max = getMax(arr);//调用获取最大值的方法
System.out.print("max=" + max);//打印
}
/**
* 取出数组中的最大值
*
* @param arr
* @return
*/
public static int getMax(int[] arr) {
int max = arr[0];//初始化最大值
for (int i = 1; i < arr.length; i++) {//数组循环
if (arr[i] > max) {//如果第i个值大于初始化的最大值 将第i个值赋给最大值
max = arr[i];
}
}
return max;//返回最大值
}转载于:https://my.oschina.net/inchlifc/blog/849201
