这是我的代码,非常简单。它应该获得10个双精度数,如果用户输入的不是双精度数,则捕获一个异常,然后从数字中取平均值:

import java.util.*;

public class QuestionOne {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        double i0, i1, i2, i3, i4,

i5, i6, i7, i8, i9;

    System.out.println("Please enter a number for each input.");
    try {
        i0 = scan.nextDouble();
        i1 = scan.nextDouble();
        i2 = scan.nextDouble();
        i3 = scan.nextDouble();
        i4 = scan.nextDouble();
        i5 = scan.nextDouble();
        i6 = scan.nextDouble();
        i7 = scan.nextDouble();
        i8 = scan.nextDouble();
        i9 = scan.nextDouble();
        double isum = i0 + i1 + i2 + i3 + i4 + i5 + i6 + i7 + i8 + i9;
        double iresult = isum / 10;
    } catch (InputMismatchException e) {
        System.out.println(e + "\nPlease, enter only numbers.");
    }

    System.out.println("The average of all the 10 numbers is " + isum);
}
}


所以,我正在尝试打印isum,但是显然不能,因为它在try-catch里面。漫长的一天后,我的大脑被炸了,当我要安定下来时,意识到我有这项工作要做。有谁知道我应该如何修改代码以能够取10双的平均值并打印出来?

最佳答案

不要尝试在try / catch之外打印出平均值;最后在try块中打印它。发生异常时,您不想打印平均值。用户输入了错误的内容,因此即使您可以打印出来,该计算也将无效。

try {
    i0 = scan.nextDouble();
    i1 = scan.nextDouble();
    i2 = scan.nextDouble();
    i3 = scan.nextDouble();
    i4 = scan.nextDouble();
    i5 = scan.nextDouble();
    i6 = scan.nextDouble();
    i7 = scan.nextDouble();
    i8 = scan.nextDouble();
    i9 = scan.nextDouble();
    double isum = i0 + i1 + i2 + i3 + i4 + i5 + i6 + i7 + i8 + i9;
    double iresult = isum / 10;

    System.out.println("The average of all the 10 numbers is " + isum);
} catch (InputMismatchException e) {
    System.out.println(e + "\nPlease, enter only numbers.");
}

10-06 14:04