public class MaxAndMin {
public static final int COUNT = 10;
public static void main(String[] args) {
/*
* 随机生成10个数并输出
*/
int[] list = new int[COUNT];
System.out.println("自动生成的10个数为:");
for (int i = 0; i < COUNT; i++) {
list[i] = (int) (Math.random() * 100 + 1);
System.out.print(list[i] + ", ");
}
System.out.println();
/*
* 求取最大、最小值并输出
*/
int[] result = getMaxAndMin(list);
System.out.println("最大值为:" + result[0]);
System.out.println("最小值为:" + result[1]);
}
/*
* 求最大值、最小值方法
*/
public static int[] getMaxAndMin(int[] list) {
int max = list[0];
int min = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] > max) {
max = list[i];
}
if (list[i] < min) {
min = list[i];
}
}
int[] result = { max, min };
return result;
}
}
试运行结果:
自动生成的10个数为:
42, 3, 24, 82, 18, 54, 54, 54, 71, 28,
最大值为:82
最小值为:3