我应该做的是每当有人放入一个字符串而不是一个整数,比如“two”,它应该说“你必须输入正数字数据!”而不是一堆错误消息。我想我已经发现了这个声明,但我不确定要尝试。以下是我迄今为止:什么投入尝试块?
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;
}
}
}
}
}
的导致异常的代码必须发生在TRY内部。此外,CATCH内的代码量和代码本身也是不好的做法。我没有时间来解释。 –