所以我們必須做一個抵押貸款計算項目,我們必須要求用戶再次計算,現在我們必須這樣做,因此每次用戶輸入任何輸入的字符串值時都會輸出錯誤消息。我以爲我做得對,但每次運行它時都會發生奇怪的事情,我無法弄清楚爲什麼,並且我知道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
}
}
}
}
有什麼事情,你們可以看到,可能是什麼問題?
請在將代碼放在此處之前縮進代碼。如果代碼冗長,特別難以閱讀和理解。 –
我無法重現您的輸出...重新編譯並再試一次;) – JBA