そこで、ユーザーに再計算を依頼する住宅ローン計算プロジェクトを作成する必要があります。次に、ユーザーがいずれかの入力に文字列値を入力するたびにエラー メッセージが出力されるようにする必要があります。私はそれを正しくやったと思っていましたが、実行するたびに奇妙なことが起こり、その理由がわかりません.Try-Catchブロックに何か問題があることを知っています.
ここに私の出力があります:http://imgur.com/cbvwM5v
ご覧のとおり、プログラムを 3 回目に実行したときに、2 番目の入力として「2」を入力しても、計算は実行されました。次に、3 回目に試したときに、負の数を入力してから「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
}
}
}
}
問題の可能性があると思われるものはありますか?