Let's get started with a program that uses a try/catch conditional!
Open Eclipse
Right-Click on your edu.buffalostate.cis425.fa10.exercises. package
Choose: File -> New -> class
In the Name: textbox type: TryCatch
Click: Finish
Copy the TryCatch.java Template (Java) code (below)
Paste that code into your new TryCatch class in the editor
Change both occurrences of put-your-lastname-here
Replace blank on after the: years = scan.nextInt();
with these lines: interest = principal * rate * years;
total = principal + interest;
payment = (total / years) / 12;
Click the Run icon
TryCatch.java Template (Java)
package edu.buffalostate.cis425.fa10.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.
*
/**
*
* @authorput-your-name-here
*
*/public class TryCatch {
public static void main( String args[] ) {
doubleprincipal = 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