Programmer: Cristine A. Salac
Program Name: User-Friendly Division
Time Started: March 6,2009
Time Finished: March 11, 2009
Program Purpose:To create a program about Exception Handling
import java.util.InputMismatchException;
public class DivisionPractice
{
public static int quotient( int numerator, int denominator )
throws ArithmeticException
{
return numerator / denominator;
} // end method for quotient
public static void main( String args[] )
{
Scanner scanner = new Scanner( System.in );
boolean continueLoop = true; // determines if more input is needed
//the try block
do
{
Try // read two numbers which are the numerator
and denominator and calculate quotient
{
System.out.print( "Enter your numerator: " );
int numerator = scanner.nextInt();
System.out.print( "Enter your denominator: " );
int denominator = scanner.nextInt();
int result = quotient( numerator, denominator );
System.out.printf( "\nResult: %d / %d = %d\n", numerator,
denominator, result );
continueLoop = false;
} // end try
catch ( InputMismatchException inputMismatchException )
{
System.err.printf( "\nException: %s\n", inputMismatchException ); // discard input so user can try again
scanner.nextLine();
System.out.println( "You must enter integers. Please try again.\n" );
} // end catch
catch ( ArithmeticException arithmeticException )
{
System.err.printf( "\nException: %s\n", arithmeticException );
System.out.println( "Zero is an invalid denominator. Please try again.\n" );
} // end catch
} while ( continueLoop ); // end do...while
} // end main
} // end class
No comments:
Post a Comment