Friday 25 October 2013

Input a number <=9999 and display it in words

import java.io.*;
class NumberInWords
{
int n,c,a[];
void input()throws IOException
{
c=0;
   BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number");
String s=x.readLine();
n=Integer.parseInt (s);
int k=n;
while(k!=0)
{
   k=k/10;
   c++;
}
a=new int[c];
k=n;
for(int i=c-1;i>=0;i--)
{
   a[i]=k%10;
   k=k/10;
}
}
String convert()
{
String w[]={"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen","Twenty","Thirty","Fourty","Fifty","Sixty","Seventy","Eighty","Ninety","Hundred","Thousand"};
String s="";
int i=c;
for(int j=0;j<c;j++)
{
if(n==0)
s=w[0];
   if(a[j]!=0)
{
if(i==4)
s=s+" "+w[a[j]]+" "+w[29];
else if(i==3)
s=s+" "+w[a[j]]+" "+w[28];
else if(i==2)
{
   if(a[j]==1)
   {
   s=s+" "+w[a[j]+9+a[j+1]];
   i=0;
   }
   else
   s=s+" "+w[a[j]+18];
}
else if(i==1)
s=s+" "+w[a[j]];
i--;
}
else
{
   i--;
   continue;
}
}
return s;
}
public static void main(String a[])throws IOException
{
   NumberInWords call=new NumberInWords();
   call.input();
   System.out.println(call.convert());
}
}

No comments:

Post a Comment