CS 111B RobustInvestApplet Example - Craig Persiko

Here is the source code for this applet:

/* Craig Persiko - CS 111B - Sample program
   RobustInvestApplet.java

   An applet to calculate the interest earned on an investment.
   Handles exceptions due to incorrect input.
*/

import javax.swing.JApplet;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;

public class RobustInvestApplet extends JApplet
{
  public void start()
  {
    String response;
    double balance;
    DecimalFormat money = new DecimalFormat("0.00");  // used to format numeric output

    response = JOptionPane.showInputDialog("How much money do you want to invest?");

    try
    {
      balance = Double.parseDouble(response);
      for(int i=0; i < 10; i++)  // each year for 10 years
        balance += balance * 0.05;  // add 5% interest to the balance.

      JOptionPane.showMessageDialog(null, "After 10 years at 5% interest, " +
                                    "you will have $" + money.format(balance));
    }
    catch(NumberFormatException nfe)
    {
      JOptionPane.showMessageDialog(null, "Please enter a number with no other characters.");
    }
    catch(NullPointerException npe)
    {
      JOptionPane.showMessageDialog(null, "Goodbye");
    }
  }
}


syntax highlighted by Code2HTML, v. 0.9

Return to CS 111B page