我应该做的是每当有人输入字符串而不是整数时,例如“二”,它应该说“您必须输入正数数据!” 而不是一堆错误消息。我想我已经弄清楚了 catch 语句,但我不确定是否可以尝试。这是我到目前为止所拥有的:
package loanpaymentfinder;
import java.text.NumberFormat;
import java.util.Scanner;
public class LoanPaymentFinder {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
NumberFormat num = NumberFormat.getCurrencyInstance();
double numInputLoan;
double numInputRate;
double numInputYears;
double numMonths;
double numRateSquared;
double numOutput;
double numRatePlusOne;
boolean finish = false;
while (true) {
//Input
System.out.print("Enter loan amount: ");
numInputLoan = Double.parseDouble(in.nextLine());
try {
} catch (NumberFormatException exception) {
System.out.println("You must enter positive numeric data!");
System.out.print("Would you like to calculate again (y/n):");
String input = in.nextLine();
if (input.equals("y")) {
continue;
} else if (input.equals("n")) {
break;
}
}
System.out.print("Enter rate: ");
numInputRate = Double.parseDouble(in.nextLine());
System.out.print("Enter number of years: ");
numInputYears = Double.parseDouble(in.nextLine());
//Checks for negitive inputs
if (numInputLoan <= 0) {
System.out.println("You must enter positive numeric data!");
System.out.print("Would you like to calculate again (y/n):");
String input = in.nextLine();
if (input.equals("y")) {
continue;
} else if (input.equals("n")) {
break;
}
} else if (numInputRate <= 0) {
System.out.println("You must enter positive numeric data!");
System.out.print("Would you like to calculate again (y/n):");
String input = in.nextLine();
if (input.equals("y")) {
continue;
} else if (input.equals("n")) {
break;
}
} else if (numInputYears <= 0) {
System.out.println("You must enter positive numeric data!");
System.out.print("Would you like to calculate again (y/n):");
String input = in.nextLine();
if (input.equals("y")) {
continue;
} else if (input.equals("n")) {
break;
}
} else {
//Math goes here
numMonths = 12 * numInputYears;
numInputRate = numInputRate / 1200;
numRatePlusOne = numInputRate + 1;
numRateSquared = Math.pow(numRatePlusOne, numMonths);
numOutput = numRateSquared / (numRateSquared - 1);
numOutput = numInputRate * numInputLoan * numOutput;
//Output
System.out.println("The mounthly payment is:");
System.out.println(num.format(numOutput));
System.out.print("Would you like to calculate again (y/n):");
String input = in.nextLine();
if (input.equals("y")) {
continue;
} else if (input.equals("n")) {
break;
}
}
}
}
}