Excersice no. 1
Date started: March 06, 2009
Date ended: March 07, 2009
Description: A program that will ask denominator and numerator and will result to quotient. Then if the user enter 'Q'/'q' the program will quit.*/
import java.util.*; //all utilities of java
public class DivisionPractice
{
//initialize a numerator and divisor to compute for the users interaction
public static double qoutient(double numerator,double divisor)
throws ArithmeticException
{
return numerator/divisor;
}
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
String ana = "ana";
char x=ana.charAt(0);
// get of character ana and stores in the x
while(x!='q'||x!='Q'){
// in this condition if the user enters the keyword q or Q the program will automatically exit
System.out.print("Please enter an integer numerator:");
// this prompt user to enter the numerator
String num=scanner.next();
try{
if(num.charAt(0)=='q'||num.charAt(0)=='Q'){
System.exit(1);
// the program will exit if the users enter q or Q if not the program will continue until the user enters the keywords
}else{
// stores the integer into the variable num and convers into the integer
double numerator=Integer.parseInt(num);
// prompt user to enter the divisor
System.out.print("Enter the divisor:");
double divisor=scanner.nextInt();
// will compute and prints out the result of the given numerator and denominator
double result=qoutient(numerator,divisor);
System.out.printf("\n Result: "+numerator+"/"+divisor+" is "+result+"\n");
}
}
// this catch block will prompt to the user if the user enters the value 0
catch(InputMismatchException inputMistmatchException)
{
double numerator=Integer.parseInt(num);
System.err.println("You can't divide "+numerator+" by 0");
System.err.printf("\n Exception: \n");
System.out.println("You must enter integers.Please try again\n");
}
// this will prompt the user that the user enters Alpha values for ex abcdef and so on
catch(NumberFormatException inputMistmatchException)
{
System.err.printf("\n Exception: ");
scanner.nextLine();
System.err.println("Alphanumeric is an invalid denominator.Please try again\n");
System.out.println("You must enter integers.Please try again\n");
}
catch(ArithmeticException arithmeticException)
{
System.err.printf("\nException:%s\n",arithmeticException);
scanner.nextLine();
System.err.println("Zero is an invalid denominator.Please try again\n");
System.out.println("You must enter integers.Please try again\n");
}
catch(IllegalFormatConversionException illegal){
System.out.println(" ");
}
}
}
}
No comments:
Post a Comment