This code is implemented and provided by Vasu, from MAIT, Delhi.
About this code : By using this code we can translate a number into a word.
For example 1 will become one
and 120 will become 1 hundred twenty
Note : This code is based on recursion.
I will post a non recursive approach to do the same thing very soon.
Till then enjoy this code.
Note : Before using this code please create a java project in eclipse and save the
code inside Conversion.java file inside src folder
import java.util.Scanner;
// Create a class consisting of main method and a calculate function
public class Conversion {
// Array of numbers for units place
static String[] unit = {"" , "one" , "two" , "three" , "four" , "five" , "six" , "seven" ,
"eight" , "nine" , "ten" , "eleven" , "twelve" , "thirteen" ,
"fourteen" , "fifteen" , "sixteen" , "seventeen" ,
"eighteen","nineteen"} ;
// Array of numbers for tens place
static String[] tens = {"" , "ten" , "twenty" , "thirty" , "forty" , "fifty", "sixty" ,
"seventy" ,"eighty" , "ninety" } ;
public static void main(String[] args) {
// Create object of Scanner Class
Scanner sc = new Scanner(System.in) ;
// Get Input From User
System.out.print("Enter the number : ");
int number = sc.nextInt() ;
// Show the Output to the user
System.out.println("Number in words : " + calculate(number));
}
public static String calculate(int n) {
// Create some cases to define range of the input number
if(n < 20) {
// Directly return the string corresponding to the number
return unit[n];
}
else if(n < 100) {
return tens[n/10] + " " + unit[n%10];
}
else if(n < 1000) {
// Apply recursion by converting the sub integer to actual integer
return unit[n/100] + " hundred " + calculate(n%100);
}
else if(n < 100000) {
// For numbers in thousands
return calculate(n/1000) + " thousand " + calculate(n%1000) ;
}
else if(n < 10000000) {
// For number in lakhs
return calculate(n/100000) + " lakhs " + calculate(n%100000) ;
}
else if(n < 1000000000) {
// For number in crore
return calculate(n/10000000) + " crore " + calculate(n%10000000) ;
}
else {
return "Number Not In The Range ! Please Try Again" ;
}
}
}
Awesome :)
ReplyDeleteBlockbuster .. gud job vasu .. calculate method is awesome