我的try-catch块有问题吗?

时间:2013-10-30 12:59:38

标签: java try-catch

因此,我们必须进行抵押贷款计算项目,我们必须要求用户再次计算,现在我们必须这样做,以便每次用户输入任何输入的字符串值时都会打印出错误消息。我以为我做对了,但是每次运行它都会发生奇怪的事情,我无法弄清楚为什么,我知道Try-Catch块出了问题。

以下是我的输出:http://imgur.com/cbvwM5v

正如你可以看到我第三次运行程序时,我输入一个“两个”作为第二个输入,它仍然进行计算。然后,我第三次尝试它,我输入一个负数,然后是“两个”,一切都按照我想要的方式工作。然后,我最后一次运行它时,我为第一个输入设置了一个正数,它仍然进行了计算,你们看到的任何东西可能都是这样做的吗?此外,我想我可能使用了错误的例外,我不确定它是什么意思,我猜对了。我应该使用NumberFormatException并且在nfe下还有一行说没有使用该值。

这是我的代码:

   package MortgageCalculation2c;

import java.text.NumberFormat;
import java.util.Scanner;
/**
 *
 * @author Akira
 */
public class MortgageCalculation2c {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
     Scanner in = new Scanner(System.in);


    double loanAmount = 0;
    double interestRate = 0;
    double numberYears = 0;
    double months;
    double monthlyPayment;
    double numerator;
    double denominator;
    double formula;
    boolean userInput = true;
    String answer = ("y");


    while (userInput) {
        try {
            loanAmount = 0;
            interestRate = 0;
            numberYears = 0;

   //prompt user for the loan amount       
    System.out.print("Enter the loan amount: ");
    loanAmount = Double.parseDouble(in.nextLine());

    //prompt the user for the interest rate
    System.out.print("Enter the rate: ");
    interestRate = Double.parseDouble(in.nextLine());

    //prompt the user for  thenumber of years
    System.out.print("Enter the number of years: ");
    numberYears = Double.parseDouble(in.nextLine());

        } catch (NumberFormatException nfe) {
            System.out.println("You must enter positive numerical data!");
        }


    //if the user enters a negative number print out a error message, if not, continue calculations
   if ((loanAmount <= 0) || (interestRate <= 0) || (numberYears <= 0)) {
        System.out.println("ALL NUMERICAL VALUES MUST BE POSITIVE!");

    } else {
        //convert the interest rate
       interestRate = interestRate / 100 / 12;

       //the number of years must be converted to months
       months = numberYears * 12;

       //numerator of the monthly payment formula
       numerator = (Math.pow(1 + interestRate, months));

       //denominator of the monthly payment formula
       denominator = ((numerator)-1);

       //the formula equals the numerator divided by the denominator
       formula = ( numerator / denominator );

       //monthly payment calculation
        monthlyPayment = (interestRate * loanAmount * formula);

         //sytem output
        NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
        System.out.println("The monthly payment is: " + defaultFormat.format(monthlyPayment));

   }

        //prompt the user if they would like to calculate the program again.
        System.out.println("Would you like to calculate again (y/n) : ");

        //if the user enters "y" the program will run again and if the user enters anything else it ends
            answer = in.nextLine();
        answer = answer.toLowerCase();
            if ( answer.equals("y")){
                userInput = true;  //tests the program if it needs to run again
            }else{
                break;  //ends the program
            }

}

}
}

你们有什么可以看到的可能是问题吗?

1 个答案:

答案 0 :(得分:0)

您的continue块中似乎需要catch,因此程序流程会回到循环中。

    ...
    } catch (NumberFormatException nfe) {
        System.out.println("You must enter positive numerical data!");
        continue;   // <---------- here
    }
    ...

如果这不是try-catch构造中的特定练习,那么最好使用Scanner的方法hasNextDouble()进行验证,nextDouble进行阅读和转换数字。

看起来像这样:

//prompt user for the loan amount       
loanAmount = enterPositiveDouble("Enter the loan amount: ")

//prompt the user for the interest rate
interestRate = enterPositiveDouble("Enter the rate: ");

//prompt the user for  the number of years
numberYears = enterPositiveDouble("Enter the number of years: ");

您将拥有一个特殊的static方法enterPositiveDouble,如下所示:

static void  enterPositiveDouble(String prompt) {
   Scanner in = new Scanner(System.in);
   boolean ok = true;
   double result = -1; 
   do {
      System.out.print(prompt);
      ok = (in.HasNextDouble() && (result = in.NextDouble()) > 0)
      if ! ok
         System.out.println("You must enter positive numerical data!");
   } while (!ok); 
}

以上不是最佳代码,只是可能解决方案的说明。