import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] nums = new int[6]; // 控制输入个数
for (int i = 0; i < nums.length; i++) {
System.err.print("请输入第" + (i+1) + "个数: ");
nums[i] = sc.nextInt(); // 此处可能抛出异常, 异常没有处理
}
int max, min;
double sum;
sum = max = min = nums[0];
for (int i = 1; i < nums.length; i++) {
if (max < nums[i]) max = nums[i];
if (min > nums[i]) min = nums[i];
sum += nums[i];
}
System.out.println("最大: " + max);
System.out.println("最小: " + min);
System.out.println("平均: " + (sum/nums.length));
}
}
异常没有处理,如果输入的是非数字会有异常抛出。
public class test{
public static void main(String [] args){
double[] arr = new double [10];
double sum = 0;
double avg = 0;
double max = arr[0];
double min = arr[0];
if (args.length == 0) {
System.out.println("请使用命令行参数"
+ "输入 10 个数");
} else {
for (int i = 0; i < args.length; i++) {
/* 将字符串参数转换为 double*/
double num = Double.parseDouble(args[i]);
arr[i] = num;
sum += arr[i];
}
for (int i = 0; i < args.length; i++) {
if(max < arr[i]){
max = arr[i];
}
if(min > arr[i]){
min = arr[i];
}
}
}
avg = sum / 10;
System.out.println("\n最大值 = "+ max);
System.out.println("\n最小值 = "+ min);
System.out.println("\n和 = " + sum);
System.out.println("\n平均值 = " + avg);
}
}
用命令行参数输入
java test 10 2 3 4 7 9 8 6 5 1
运行结果
最大值 = 10.0
最小值 = 0.0
和 = 55.0
平均值 = 5.5
cairen a
/*
* xiangjun_z
*/
package test;
import java.util.Random;
/**
*
* @author m
*/
public class Counter {
int[] p;
int max;
int min;
int average;
String description="";
Counter(int[] p) {
this.p = p;
if (p != null) {
max = p[0];
min = p[0];
int tt = 0;
for (int i = 0; i < p.length; i++) {
if (max < p[i]) {
max = p[i];
}
if (min > p[i]) {
min = p[i];
}
tt+=p[i];
}
average=tt/p.length;
description="max="+max+"\nmin="+min+"\n";
description+="average="+average;
}
}
public String getDescription(){
return description;
}
public static void main(String[] args) {
int mpLength = 30;
System.out.println("总计有元素"+mpLength+"个");
int[] mp = new int[mpLength];
Random r = new Random();
for (int i = 0; i < mp.length; i++) {
mp[i] = r.nextInt();
System.out.print(mp[i]+" ");
}
Counter c = new Counter(mp);
System.out.println("the result is:");
System.out.println(c.getDescription());
}
}