I don't understand why this happens in this code.
The only difference I see is that the first two numbers are doubles and the third is an int, but the exception is caught for the first two and not the third. The third throws the NumberFormatException.
But if I hit Cancel BEFORE parseInt() is called, why am I getting a NumberFormatException?
I couldn't find anything in the docs that might explain this.
Thanks in advance.
import javax.swing.*;
import java.text.*;
public class FutureValue
{
public static void main(String[] args)
{
String choice = "";
try
{
while(!(choice.equalsIgnoreCase("x")))
{
//Works as expected here.
String paymentString = JOptionPane.showInputDialog(null,
"Enter monthly payment: ", "Future Value", JOptionPane.PLAIN_MESSAGE);
double monthlyPayment = Double.parseDouble(paymentString);
//Works as expected here.
String rateString = JOptionPane.showInputDialog(null,
"Enter yearly interest rate: ", "Future Value", JOptionPane.PLAIN_MESSAGE);
double interestRate = Double.parseDouble(rateString);
double monthlyInterestRate = interestRate/12/100;
//NumberFormatException thrown here.
String yearsString = JOptionPane.showInputDialog(null,
"Enter number of years: ", "Future Value", JOptionPane.PLAIN_MESSAGE);
int years = Integer.parseInt(yearsString);
int months = years * 12;
double futureValue = calculateFutureValue(monthlyPayment,
months, monthlyInterestRate);
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMinimumFractionDigits(2);
String message =
"Monthly payment: " + currency.format(monthlyPayment) + "\n"
+ "Yearly interest rate: " + percent.format(interestRate/100) + "\n"
+ "Number of years: " + years + "\n"
+ "Future value: " + currency.format(futureValue) + "\n\n"
+ "To continue, press Enter.\n"
+ "To exit, enter 'x': ";
choice = JOptionPane.showInputDialog(null,
message, "Future Value", JOptionPane.PLAIN_MESSAGE);
}//end while
}//end try
catch(NullPointerException e)
{
System.exit(0);
}//end catch
System.exit(0);
}//end main
private static double calculateFutureValue(double monthlyPayment,
int months, double interestRate)
{
int i = 1;
double futureValue = 0;
while (i <= months)
{
futureValue = (futureValue + monthlyPayment) *
(1 + interestRate);
i++;
}//end while
return futureValue;
}//end calculateFutureValue
}//end class