Thursday, March 5, 2009

User-Friendly Division by: Maribelle P. Lacno

/* Programmer: Maribelle Lacno
  * Program name: DivisionPractice
  * Subject: IT134_Computer Programming 3 
  * Instructor: Mr. Dony Dongiapon 
  * Date Started: 03/06/09 
  * Date Finished: 03/09/09 
  * Purpose: To create a program that will reinforce 
  * my learnings and knowledge in Exception handling. 
*/


import java .util.*;
import java.io.*;


public class DivisionPractice {
 //create the quotient() method that will compute the numerator and divisor
 public static double quotient(double numerator, double divisor)throws
 ArithmeticException{
  return numerator/divisor;
 }

 public static void main(String[] args){
  //declare a scanner that will get the value of the user's input
  Scanner scan = new Scanner(System.in);
  double num, div, ans;
   //initialize variable c to be equal to 'm'
  char c='m';
  do{
   //ask the user to input the numerator
   System.out.print("\nEnter numerator: ");
   //get and store the numerator to variable n as a String
   String n=scan.next();
   //get the first character of n and store it in variable x
   char x=n.charAt(0);
   try{
   //if x is equal to 'q' or 'Q', the program will exit
   if(x=='q'||x=='Q'){
   System.exit(0);
   }else{
    //convert the String value of n to integer value and store it in variable num
    num=Integer.parseInt(n);
    //ask the user to input the divisor
     System.out.print("\nEnter divisor: ");
    //get and store the divisor to variable d as a String
    String d=scan.next();
    //get the first character of d and store it in variable y
    char y=d.charAt(0);
    //if y is equal to 'q' or 'Q', the program will exit
    if(y=='q'||y=='Q'){
     System.exit(0);
    }else{
     //convert the String value of d to integer value and store it in variable div
     div = Integer.parseInt(d);
     //call the method quotient() to compute the variable ans
     ans=quotient(num,div);
     //the program will print the result
      System.out.println();
      System.out.print(num+"/"+div+" is "+ans);
      System.out.println();
    }
   }
  }
  catch(NumberFormatException numberFormat){
    //print the error message and tell the user to input again
    System.err.printf("\nYou entered bad data.\nPlease try again.");
  }
  catch(ArithmeticException arithmetic){
    //convert the String value of n to integer value and store it in variable num
    num=Integer.parseInt(n);
    //print the error message
    System.err.printf("\nYou can't divide "+num+" by 0");
   }
  }
  while(c!='q');
  }
}

No comments:

Post a Comment