Tuesday, March 11, 2014

Number to Word Converter in Java


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

public class NumberToword

{
  private static int n = 0;
  private static NumberToword obj = null;
  private static Scanner s = null;

 //This method is used for getting the result
  public void result(int n,String ch)

     {

   String one[]={

     " "," one"," two"," three"," four"," five"," six"," seven"," eight"," Nine"," ten"," eleven"," twelve"," thirteen"," fourteen","fifteen"," sixteen"," seventeen"," eighteen"," nineteen"};

   String ten[]={" "," "," twenty"," thirty"," forty"," fifty"," sixty","seventy"," eighty"," ninety"};

   if(n>19) {
    System.out.print(ten[n/10]+" "+one[n%10]) ;
    }
  
   else {
    System.out.print(one[n]);
        }  
  
       if(n>0)
         System.out.print(ch);
       }
 //This method is used for processing the input

    public void processInput(){
               
     obj.result((n/1000000000)," Hundred");
     obj.result((n/10000000)%100," crore");
     obj.result(((n/100000)%100)," lakh");
     obj.result(((n/1000)%100)," thousand");
     obj.result(((n/100)%10)," hundred");
     obj.result((n%100)," ");
  
    }
  
 //This method Used for getting input
    public int getInput(){
      int i = 0;
      s =new Scanner(System.in);
      System.out.println("Enter an integer number: ");
      i = s.nextInt();
      return i;
    }
  
      public static void main(String[] args) throws IOException
      {
      
        String emptyArg[] = null;
        int startLimit = 0;
        int endLimit = 999999999;
      
       try {
        obj =new NumberToword();
        n = obj.getInput();
       if( n <= startLimit && n < endLimit ){
       
        System.out.println("Enter numbers between 0 to 999999999");
        NumberToword.main(emptyArg);
       }
       else
          {
        obj =new NumberToword();
        System.out.println("After conversion number in words is :");
        obj.processInput();
            
          }
       }
       catch(InputMismatchException e) {
        //e.printStackTrace();
        System.out.println("Enter numbers between 0 to 999999999");
        NumberToword.main(emptyArg);
       
       }
            
      }
}