Program to print Numbers in Words
Question : Print a given number in Words
Write a program to print a number and convert it into words. Suppose we enter a number- 132 the output should be "one hundred thirty two"
- 5234 the output should be "five thousand two hundred thirty four"
- 90 the output should be "ninety"
Program : Print Numbers in Words
import java.util.Scanner; class NumberInWords{ String once[] = {"zero","one","two","three","four","five","six","seven","eight","nine"}; String tens[] = {"ten","twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninty"}; public static void main(String args[]){ NumberInWords obj = new NumberInWords(); System.out.println("Enter the number to be converted to words"); Scanner sc = new Scanner(System.in); System.out.println(obj.getNumber(sc.next())); } public String getNumber(String num){ String words=""; int digit = Integer.parseInt(num.charAt(0)+""); switch(num.length()) { case 3: return words = once[digit] + " hundered "+ getNumber(num.substring(1)); case 2: if(Integer.parseInt(num) % 10 != 0){ return words = tens[digit-1] + getNumber(num.substring(1)); }else{ return words = tens[digit-1]; } case 1: if(digit != 0) return words += " " + once[digit]; default: return words += getNumber(num.substring(0,num.length()-3)) + " thousand " + getNumber(num.substring(num.length()-3)) ; } } }
Enter the number to be converted to words 456 four hundered fifty six
Enter the number to be converted to words 789456 seven hundered eighty nine thousand four hundered fifty six
Enter the number to be converted to words 50 fifty
Logic : Important Points To Remember
We will need to have the numbers 1-9 in words in an array. We will also need the numbers like 10,20 up to 90 in words. We need them because they are the root words that can be used to print numbers in words. Using these we can generate a large range of numbers in words.- Now, if the have a number string of length 1 i.e. "case 1" this means that the number is of one digit only and we can print its value from array "once[]".
- If the length of the number string is 2 i.e. "case 2" this means this number is between 10 to 99. Now we check if the number is divisible by 10 or not.
- if number is divisible by 10 like 20, 80 etc, we will get the words from the array "tens[]".
- if number is not divisible by 10 like 55,72 etc, we will print tens's digit from array "tens[]" and once digit from array "once[]".
- If the length of the number is 3 we print the number's hundred's digit from array "once[]" add "hundred" and then call the method recursively.
- For the numbers greater than 9999 we will print the numbers as 1000's and then proceed to the normal cases stated above. In this case we divide the number in two parts, e.g for number 123456 we divide the number 123 and 456, the first part prints "one hundred twenty three" then adds "thousand" and then adds the second part "four hundred fifty six". This makes our complete number.
No comments: