java编程:编程从键盘输入一维数组 int a[20]中的20个整数,并求此数组元素的最大值、最小值、平均值及所编程从键盘输入一维数组 int a[20]中的20个整数,并求此数组元素的最大值、最小值、平
来源:学生作业帮助网 编辑:作业帮 时间:2024/11/19 15:25:06
java编程:编程从键盘输入一维数组 int a[20]中的20个整数,并求此数组元素的最大值、最小值、平均值及所编程从键盘输入一维数组 int a[20]中的20个整数,并求此数组元素的最大值、最小值、平
java编程:编程从键盘输入一维数组 int a[20]中的20个整数,并求此数组元素的最大值、最小值、平均值及所
编程从键盘输入一维数组 int a[20]中的20个整数,并求此数组元素的最大值、最小值、平均值及所有 元素之和.
java编程:编程从键盘输入一维数组 int a[20]中的20个整数,并求此数组元素的最大值、最小值、平均值及所编程从键盘输入一维数组 int a[20]中的20个整数,并求此数组元素的最大值、最小值、平
看看谁的效率高过我
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Cat {
public static void main(String args[]){
final int length = 20;
int[] ary = new int[length];
int sum = getDataAndCalcSumFromInput(ary);//填充数组,并且返回总和
Arrays.sort(ary);//从小到大升序排列数组
int min = ary[0];//最小值为第一个
int max = ary[length-1];//最大值必定为最后一个元素
double average = (double)sum / length;//求平均
System.out.println("Min is: " + min);
System.out.println("Max is: " + max);
System.out.println("Sum is: " + sum);
System.out.println("Average is: " + average);
}
private static int getDataAndCalcSumFromInput(int[] ary) {
int count = 0;
int sum = 0;
while(count < ary.length){
System.out.println("Please input an integer for array " + count );
Scanner scanner = new Scanner(System.in);
try {
ary[count] = scanner.nextInt();
sum += ary[count++];//累计和
} catch (InputMismatchException e) {
System.out.println("Invalid digit number in format, please input again!");
}
}
return sum;
}
}
---------------
Please input an integer for array 0
a
Invalid digit number in format, please input again!
Please input an integer for array 0
1
Please input an integer for array 1
cddd
Invalid digit number in format, please input again!
Please input an integer for array 1
2.5
Invalid digit number in format, please input again!
Please input an integer for array 1
0
Please input an integer for array 2
2
Please input an integer for array 3
3
Please input an integer for array 4
4
Please input an integer for array 5
5
Please input an integer for array 6
6
Please input an integer for array 7
7
Please input an integer for array 8
8
Please input an integer for array 9
9
Please input an integer for array 10
10
Please input an integer for array 11
11
Please input an integer for array 12
12
Please input an integer for array 13
13
Please input an integer for array 14
14
Please input an integer for array 15
15
Please input an integer for array 16
16
Please input an integer for array 17
17
Please input an integer for array 18
18
Please input an integer for array 19
19
Min is: 0
Max is: 19
Sum is: 190
Average is: 9.5