如何修改我的代码以在尝试捕获中初始化的外部打印变量?

时间:2019-03-13 03:45:02

标签: java exception try-catch

这是我的代码,非常简单。它应该获得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双的平均值并打印出来?

2 个答案:

答案 0 :(得分:1)

请勿尝试在尝试/捕获之外打印平均值;最后在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.");
}

答案 1 :(得分:0)

如果有异常,将不会有任何结果,因此我将在try块中进行打印。另外,根据您的打印对帐单,您要打印结果(而不是总和)。

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