public class GetMaxDemo {
/**
* 我写了个Demo,利用数组,再多元素之间比较大小,都OK
* @param args
*/
public static void main(String[] args) {
// 需要比较的值
int[] a = { 1, 2, 3, 4 };
// 定义一个变量,保存最大值
int max = 0;
// 依次遍历数组的每个元素
for (int i = 0; i < a.length; i++) {
// 如果当前元素比最大值要大的话,就把当前元素赋给最大值
if (a[i] > max) {
max = a[i];
}
}
System.out.println("最大值为:" + max);
}
} |