异常处理,首先尝试/捕获块不会重复,直到接受正确的输入

时间:2018-04-25 01:00:09

标签: java exception-handling

编写一个程序,询问用户的输入,以计算他们是否能负担得起汽车。当提示用户输入汽车价格时,我的try / catch块无法正常工作。程序继续在第一个try / catch块之后运行代码。值得注意的是,所有其他代码都按预期工作(程序要求输入大量双打,只有第一个不起作用)

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Scanner;


public class Minimal {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Car car = new Car();
        Scanner sc = new Scanner(System.in);
        PrintWriter out;
        try {
            out = new PrintWriter("number.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }
        System.out.println("What is the msrp?");

        try 
        {
            double price = sc.nextDouble();
            car.setStickerPrice(price);
            out.println(price);
        }   
        catch (InputMismatchException e) 
        {
            System.out.println("The MSRP is a numberical value, please reenter a number.");
            out.println("The MSRP is a numberical value, please reenter a number.");
        }
        System.out.println("What is your down payment?");
        out.println("What is your down payment?");





        double pay = 0;
        while (true) {

            try {
                pay = Double.parseDouble(sc.next());
                break; // will only get to here if input was a double
            } catch (NumberFormatException ignore) {
                 System.out.println("Invalid input, input a numerical value: ");  
            }
        }



        car.setDownPayment(pay);
        out.println(pay);
        car.setOutTheDoor();
        System.out.println(
                "Please enter your interest rate (APR) as a decimal value. For example, an interest rate of 3% would be entered as '.03.'");
        out.println(
                "Please enter your interest rate (APR) as a decimal value. For example, an interest rate of 3% would be entered as '.03.'");




        double rate = 0;
        while (true) {

            try {
                rate = Double.parseDouble(sc.next());
                break; // will only get to here if input was a double
            } catch (NumberFormatException ignore) {
                 System.out.println("Invalid input, input a numerical value: ");  
            }
        }

    }

}

输出:

什么是msrp?

建议零售价是一个数字值,请重新输入一个数字 你的首付款是多少? 输入无效,输入数值:

输入无效,输入数值:

输入无效,输入数值:
1
请输入您的利率(APR)作为小数值。例如,3%的利率将输入为“.03” 摹
输入无效,输入数值:

输入无效,输入数值:
5

1 个答案:

答案 0 :(得分:0)

这不是try / catch阻止的工作方式。如果您需要这种行为,那么您需要将try / catch放在循环中。

while(true) {
    try { ask question; break; }
    catch { error handling }
}

你只会打破"休息"如果问题没有引发异常。

同一件事的略有不同的版本可能更容易理解......

bool inputValid = false;
while(!inputValid){
    try { ask question; inputValid = true; }
    catch { error handling }
}