简体   繁体   English

我的try-catch代码块做错什么了吗?

[英]Am I doing something wrong with my try-catch block?

So we have to make a mortgage calculation project where we have to ask the user to calculate again and now we have to make it so it prints out a error message every time the user enters a string value for any of the inputs. 因此,我们必须创建一个抵押贷款计算项目,在该项目中,我们必须要求用户再次进行计算,现在我们必须进行抵押贷款计算,以便每次用户为任何输入输入字符串值时,它都会打印出错误消息。 I thought I did it right but something strange happens every time I run it and I can't figure out why and I know it's something wrong with the Try-Catch blocks. 我以为我做对了,但是每次运行它都会发生一些奇怪的事情,我不知道为什么,而且我知道Try-Catch块有问题。

Here are my outputs: http://imgur.com/cbvwM5v 这是我的输出: http : //imgur.com/cbvwM5v

As you can see the third time i run the program I enter a "two" as the second input and it still did the calculations. 如您所见,我第三次运行程序,我输入“ 2”作为第二个输入,它仍然进行了计算。 Then, the third time I tried it, I entered a negative number then a "two" and everything worked the way I wanted it to. 然后,第三次尝试时,我输入了一个负数,然后输入了一个“两个”,一切按我希望的方式进行。 Then, the last time I ran it I put a positive number for the first input and it still did the calculations, anything you guys see that might be doing this? 然后,上一次我运行它时,我在第一个输入中输入了一个正数,但仍然进行了计算,你们看到的任何内容可能正在执行此操作吗? Also, I think I may have used the wrong exception, I'm not uite sure what it means, I just guessed. 另外,我想我可能使用了错误的异常,我不确定是什么意思,我只是猜到了。 am I supposed to user NumberFormatException and there is also a line under nfe saying that the value is not being used. 我应该使用NumberFormatException,并且在nfe下还有一行表示未使用该值。

Here's my code: 这是我的代码:

   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
            }

}

}
}

Is there anything that you guys can see that might be the problem? 你们有什么看到的可能是问题吗?

It seems you need continue in your catch block, so the program flow goes back to the loop. 似乎您需要在catch块中continue ,所以程序流程返回到循环。

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

If this is not a specific exercise in try-catch construct, it be would be better to use Scanner 's method hasNextDouble() for validatiing and nextDouble for reading and converting the numbers. 如果这不是try-catch构造中的特定练习,则最好使用Scanner的方法hasNextDouble()进行验证,并使用nextDouble来读取和转换数字。

It will look something like this: 它看起来像这样:

//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: ");

and you will have a special static method enterPositiveDouble like following: 并且您将有一个特殊的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); 
}

The above is not an optimal code but just the illustration of a possible solution. 上面的代码不是最佳代码,而只是可能解决方案的说明。

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

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