简体   繁体   English

Java异常处理问题

[英]Java Exception Handling issues

My final project for Object Oriented Programming is a program employing objects, classes, and user inputs to calculate whether the user can afford a car based on their income and a user-defined percentage of their monthly income that the total cost of ownership of the car is not to exceed. 我针对面向对象程序设计的最后一个项目是一个使用对象,类和用户输入的程序,用于根据用户的收入以及用户定义的月收入(即汽车总拥有成本)的百分比来计算用户是否可以负担得起汽车不超过。 The program functions as desired, but i need to implement exception handling to catch incorrect inputs (ie string characters in a double field). 该程序可以根据需要运行,但是我需要执行异常处理以捕获不正确的输入(即,双字段中的字符串字符)。 My tutor and I cannot figure out how to properly catch the exceptions and prompt the user to reenter an appropriate value. 我和我的导师无法弄清楚如何正确捕获异常并提示用户重新输入适当的值。

Here's the code I need to handle exceptions for: 这是我需要处理异常的代码:

System.out.println("What is the price of the car?");
    car.setPrice(sc.nextDouble());
    System.out.println("What is your down payment?");
    car.setDownPayment(sc.nextDouble());
    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.'");
    car.setRate(sc.nextDouble());
    System.out.println("What is the maturity of your loan? The maturity of your loan is the length of time in months over which the loan will be paid.");
    car.setMaturity(sc.nextInt());
    car.setPayment();

    System.out.println("The car you've chosen is a" + car.getModelName());
    System.out.println("The MSRP is: $" + car.getStickerPrice());
    System.out.println("The down payment is: $" + car.getDownPayment());
    System.out.println("The OTD price is: $" + car.getOutTheDoor());
    System.out.println("The interest rate is: " + car.getRate());
    System.out.println("The maturity is: " + car.getMaturity());
    System.out.println("Your monthly payment is: $" + car.getPayment());

    System.out.println("Let's see if you can afford a " +car.getModelName() + "!");
    while(personalFinance.getSalary() <= 0)
    {
        System.out.println("What is your annual salary after taxes and deductions?");
        personalFinance.setSalary(sc.nextDouble());
        if(personalFinance.getSalary() <= 0)
        {
            System.out.println("You need to make money to afford a car! Please reenter a value that is greater than 0.");
        }       
    }


    System.out.println("Approximately how many miles do you drive a year?");
    car.setMilesDriven(sc.nextInt());
    System.out.println("What is the average fuel efficiency of the " + car.getModelName() + "?");
    car.setFuelEfficiency(sc.nextInt());
    System.out.println("What is the average cost of fuel in your area?");
    car.setPricePerGallon(sc.nextDouble());
    System.out.println("What is your annual insurance rate?");
    car.setInsurance(sc.nextDouble());
    System.out.println("What is the percentage of your monthly income that you do not want your monthly cost of ownership to exceed? Enter the percent as decimal value. For example, if you do not want your monthly payment to exceed 20% of your monthly income, then enter .20.");
    personalFinance.setMonthlySalary(sc.nextDouble());

If you are using Java 1.8, you can create a generic helper method for the handling of the InputMismatchException that occurs when the user enters some string that cannot be converted to the desired type. 如果您使用的是Java 1.8,则可以创建一个通用的辅助方法来处理InputMismatchException ,该方法在用户输入无法转换为所需类型的字符串时发生。

public static <T> T nextValid(final String prompt, final Scanner sc, final Function<Scanner, T> nextFn) {
    do {
        System.out.println(prompt);
        try {
            return nextFn.apply(sc);
        } catch (InputMismatchException e) {
            System.out.println("Invalid input, please try again.");
            sc.next(); // skip invalid token.
        }
    } while (true);
}

And you use it like this: 您可以像这样使用它:

int x = nextValid("Give me an integer:", sc, Scanner::nextInt);
double y = nextValid("Now a double:", sc, Scanner::nextDouble);

Then it will keep asking until a valid input from the user. 然后它将一直询问,直到来自用户的有效输入为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM