所以我们必须做一个抵押计算项目,我们必须要求用户再次计算,现在我们必须让它在每次用户输入任何输入的字符串值时打印出错误消息。我认为我做对了,但是每次运行它时都会发生一些奇怪的事情,我不知道为什么,我知道 Try-Catch 块有问题。
这是我的输出:http: //imgur.com/cbvwM5v
正如您所看到的,第三次运行程序时,我输入了“二”作为第二个输入,它仍然进行了计算。然后,第三次尝试时,我输入了一个负数,然后输入了一个“2”,一切都按照我想要的方式进行。然后,我最后一次运行它时,我为第一个输入输入了一个正数,它仍然进行计算,你们看到的任何东西可能会这样做吗?另外,我想我可能使用了错误的异常,我不确定这意味着什么,我只是猜测。我应该用户 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
}
}
}
}
你们有什么可以看到的可能是问题的地方吗?