bsc Logo

Let's get started with a program that uses a try/catch conditional!

  1. Open Eclipse
  2. Right-Click on your edu.buffalostate.cis425.fa19.exercises. package
  3. Choose: File -> New -> class
  4. In the Name: textbox type: TryCatch
  5. Click: Finish
  6. Copy the TryCatch.java Template (Java) code (below)
  7. Paste that code into your new TryCatch class in the editor
  8. Change both occurrences of put-your-lastname-here
  9. Replace blank on after the:
    years = scan.nextInt();
    with these lines:
    interest = principal * rate * years;
    total = principal + interest;
    payment = (total / years) / 12;
  10. Click the Run icon

TryCatch.java Template (Java)

package edu.buffalostate.cis425.fa19.exercises.put-your-lastname-here;

import java.text.DecimalFormat;
import java.util.Scanner;

/**
 *
 * File: TryCatch.java
 *
 * Create a Java class named TryCatch prompts the user for input and display an
 * exception error if the user enters any non-numeric input.
 * 
 * 1) This class contains a main( ) method which uses a try/catch conditional
 *    to accept only numeric input from the user for the loan amount, interest
 *    rate, and loan terms and prints out the monthly payment amount.
 *
/**
 *
 * @author put-your-name-here
 *
 */

public class TryCatch {

  public static void main( String args[] ) {
    double principal = 0, rate = 0, years = 0, interest = 0, total = 0, payment = 0;
    while (true) {
      // create a Scanner object for user input
      Scanner scan = new Scanner(System.in);
      try { 
        System.out.print("Enter the loan amount: ");
        principal = scan.nextDouble();  
        System.out.print("Enter the interest rate: ");
        rate = scan.nextDouble();
        System.out.print("Enter the loan term (in years): ");
        years = scan.nextInt();
        ___________________________________________
        ___________________________________________
        ___________________________________________
        DecimalFormat df = new DecimalFormat ("0.00");
        System.out.println("Monthly payment: $" + df.format(payment));
      } catch (Exception exc) {
        // if user did not enter a number
        System.out.println(exc);
      }           
      scan.close();
      System.exit(0);
    } // end while
  }
}

TryCatch Class Output

Enter the loan amount: 1000
Enter the interest rate: .2
Enter the loan term (in years): 10
Monthly payment: $25.00