程序代码
/**
* 功能:获取数组中元素的最大值
* 作者:孤梦
* 日期:2022年03月12日
*/
public class practice04 {
public static void main(String[] args) {
int[] arr = {
4, 5, 7, 2, 8, 3, 56}; // 定义一个数组
int max = getMax(arr); // 调用获取最大值的方法
System.out.println("max = " + max); // 打印最大值
}
static int getMax (int[] arr) {
int max = arr[0]; // 定义变量max用于记住最大数,首先假设第一个元素为最大值
for (int x = 2; x < arr.length; x++) {
// 通过for循坏遍历数组中的元素
if (arr[x] > max) {
// 比较arr[x]的值是否大于max
max = arr[x]; // 条件成立,将arr[x]的值赋予max
}
}
return max; // 返回最大值
}
}