gcp Logo

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

  1. Login to your Repl.It account.
  2. Click on: Languages
  3. In the Popular section choose: Java: A concurrent, class-based, statically typed object-oriented language.
  4. Click the pencil icon next to your repl name.
  5. In the Default name: input box type: TryCatch
  6. Delete all the lines of code provided as an example.
  7. Copy the TryCatch.java Template (Java) code (below)
  8. Paste that code into your new TryCatch class in the editor
  9. Change the @author put-your-username-here
  10. Replace blank on after the:
    years = scan.nextInt();
    with these lines:
    interest = principal * rate * years;
    total = principal + interest;
    payment = (total / years) / 12;
  11. Click the Run icon

TryCatch.java Template (Java)

/**
 *
 * 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
 *
 */
 
import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {

  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