Digit To Words
Digit To Words
/*
* ashking13th@gmail.com
* javaprogramsbyashking13th.blogspot.com
* ashkingjava.blogspot.com
*/
/*
* QUESTION
*
* Design a program in java to :
* Define a class Convert to express digits of an integer in words.
* The class details are given below:
*
* CLASS NAME : Convert
* DATA MEMBER
*
* n :integer whose digit are to be expressed in words.
*
* MEMBER METHODS
*
* Convert() :default constructor
* void inpnum() :to accept value for n
* void extdigit(int) :to extract the digits of 'n' using RECURSION
* and by invoking function num_to_words(int)
* print digits of intrger 'n'in words
* void num_yo_words :to display digits of an integer n in words
*
* SPECIFY THE CLASS GIVING DETAILS OF THE CONSTRUCTOR AND FUNCTIONS.
* MAIN METHOD IS NOT REQUIRED.
*/
import java.io.*;
public class Convert
{
int n;//DECLARING DATA MEMBER
DataInputStream d=new DataInputStream(System.in);
public Convert()//DEFAULT CONSTRUCTOR
{
n=0;
}
void inpnum()throws IOException
{
System.out.println("ENTER NUMBER");
n=Integer.parseInt(d.readLine());//INPUTING n
extdigit(n);
}
//RECURSIVE METHOD
void extdigit(int a)
{
if(a>0)
{
Aug 12, 2014 11:35:18 PM
Class Convert (continued) 2/3
int z=a%10;//EXTRACTING LAST DIGIT
extdigit(a/10);
/*
* MAKING USE OF RECURSION BY CALLING THE FUNCTION ITSELF
* INSIDE IT .
*
*/
num_to_words(z);//PRINTING THE WORD BY CALLING FUNCTION
}
}
public void num_to_words(int b)
{
//TO PRINT DIGIT IN WORDS
String name[]={" ZERO"," ONE"," TWO"," THREE"," FOUR"," FIVE"," SIX","
SEVEN"," EIGHT"," NINE"};
System.out.print(name[b]+" ");
//printing the required word
}//end of num_to_words
// main() NOT REQUIRED AS PER QUESTION
public void main() throws IOException
{
Convert obj=new Convert();//creating object
obj.inpnum(); //calling functions through object
obj.extdigit(n); //calling functions through object
}//end of main
}//end of class
/*
* ALTERNATIVE METHOD FOR digit_to_words(int)
*
*
* void num_to_words(int b)
{
//TO PRINT DIGIT IN WORDS
switch(b)
{
case 0:System.out.print(" ZERO");
break;
case 1:System.out.print(" ONE");
break;
case 2:System.out.print(" TWO");
break;
case 3:System.out.print(" THREE");
break;
case 4:System.out.print(" FOUR");
break;
case 5:System.out.print(" FIVE");
break;
case 6:System.out.print(" SIX");
break;
case 7:System.out.print(" SEVEN");
Aug 12, 2014 11:35:18 PM
Class Convert (continued) 3/3
break;
case 8:System.out.print(" EIGHT");
break;
case 9:System.out.print(" NINE");
break;
}//end of switch
}
*
*/
Aug 12, 2014 11:35:18 PM