程序代码:
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JOptionPane;
public class Calc3 {
public double parseDou(String str) {
double j = 0;
try {
j = Double.parseDouble(str);
}
catch(NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "对不起,你输入的格式有误,请重新输入!!!");
String str1 = JOptionPane.showInputDialog(null, "请再次输入一个数");
j = parseDou(str1);
}
return j;
}
public static void main(String[] args) {
double[] arr = new double[10];
double temp = 0;
double average = 0;
double sum = 0;
Calc3 Calc = new Calc3();
ArrayList<Double> list = new ArrayList<Double>();
for (int i=0; i<arr.length; i++){
String str = JOptionPane.showInputDialog(null, "请输入一个数");
temp = Calc.parseDou(str);
list.add(temp);
sum += temp;
System.out.print(temp +" ");
}
System.out.println();
average = sum / 10;
System.out.println("平均值 = " +average);
Collections.sort(list);
System.out.println("最大值 = " +list.get(list.size() - 1)+ "最小值 = " +list.get(0));
}
}
import java.util.Collections;
import javax.swing.JOptionPane;
public class Calc3 {
public double parseDou(String str) {
double j = 0;
try {
j = Double.parseDouble(str);
}
catch(NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "对不起,你输入的格式有误,请重新输入!!!");
String str1 = JOptionPane.showInputDialog(null, "请再次输入一个数");
j = parseDou(str1);
}
return j;
}
public static void main(String[] args) {
double[] arr = new double[10];
double temp = 0;
double average = 0;
double sum = 0;
Calc3 Calc = new Calc3();
ArrayList<Double> list = new ArrayList<Double>();
for (int i=0; i<arr.length; i++){
String str = JOptionPane.showInputDialog(null, "请输入一个数");
temp = Calc.parseDou(str);
list.add(temp);
sum += temp;
System.out.print(temp +" ");
}
System.out.println();
average = sum / 10;
System.out.println("平均值 = " +average);
Collections.sort(list);
System.out.println("最大值 = " +list.get(list.size() - 1)+ "最小值 = " +list.get(0));
}
}
----------------解决方案--------------------------------------------------------
解释一下我上面的代码:
1、对于输入格式的判断,按楼主的写法,如果在catch中,仍然输入不合法的数字,那么程序就over了,因为输入错误的次数无法预估,所以仅仅catch一次是不够的,所以我将转换数字单独作为一个方法,使用了递归。楼主这个错误是致命的,是一定要修正的
2、楼主没有必要先把数存起来,等所的数都存好以后,再循环数组,相加求和,可以一边存,一边加,这样会少一个求和的循环,提高效率
3、我把数组换成了ArrayList,仅仅为了偷懒,想直接使用java提供的排序方法,不想自己写排序的方法而已
----------------解决方案--------------------------------------------------------