带有catch语句和崩溃的方法中的无限循环

时间:2017-06-09 22:12:32

标签: java try-catch

我正在编写一个程序来确定旅行的汽油里程。但是,我想确保用户不会在提示符下输入字符串或字符,并确保用户输入Double。我设置了一个try / catch,就像我在其他程序中没有任何问题一样,但是这个给了我一些问题。但程序会循环返回该方法然后崩溃。我已经尝试将它放在while循环中,并尝试将每个输入放在一个单独的try-catch中,但没有运气。

private static double[] gas(){
    double gasCost[] = new double[3];
    System.out.println("********************************************************");
    System.out.print("What is the current price of gas per gallon, ie...2.84: $");
    try{
        gasCost[0] = input.nextDouble();
        System.out.print("On average, how many miles to the gallon does your vehicle get, ie...22.5: ");
        gasCost[1] = input.nextDouble();
        gasCost[2] = gasCost[0] / gasCost[1];             
    } catch (Exception e) {
        System.out.println("\nERROR!! Invalid input, please try again!\n");
        gas();
    }
    return gasCost;
}

1 个答案:

答案 0 :(得分:0)

将此代码添加到您的代码中以进行调试,您将看到它确实失败的原因:

try{
    //...         
} catch (Exception e) {
    System.err.println(e.toString()); // < added this
    System.out.println("\nERROR!! Invalid input, please try again!\n");
    gas();
}

至少,您需要在每次拨打input.nextLine()后拨打nextDouble才能使用该线路。

完整的注意事项,不要为此目的使用数组。很难看出哪个指数与什么价值有关。定义一个类并返回它。

class Gas {
    private final double cost;
    private final double mileage;

    Gas(double cost, double mileage) {
        this.cost = cost;
        this.mileage = mileage;
    }

    double getEfficiency() {
        return cost / mileage; // check for divide by zero too
    }

    //getters for the other fields (maybe)
}

你的气体方法:

private static Gas gas(){
    //...

    return new Gas(cost, mileage);
}
相关问题