Java program to display number in words
In this context, we are going to learn how to write a program in Java to display the number in words.
Input: If user initializes n=24 it will print Twenty Four and if n=268 Two Sixty Eight and so on.
Java Program to print or display number in words
class Calculate { public static void main(String[] args) { int n=71; System.out.print(n); //Object created of class numConWords numConWords nw = new numConWords(); nw.genWords((n / 1000000000), " Hundred"); nw.genWords((n / 10000000) % 100, " crore"); nw.genWords(((n / 100000) % 100), " lakh"); nw.genWords(((n / 1000) % 100), " thousand"); nw.genWords(((n / 100) % 10), " hundred"); nw.genWords((n % 100), " "); } } class numConWords { void genWords(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); } }
OUTPUT: 71 Seventy One
So the user will initialize the number in the program.
Steps maintained:
- We have created a new class name numConWords and in the class the method genWords which will generate the words as per the number.
- In the function which takes two parameters, we have initialized an array which contains one to nineteen and in the second array contains Twenty, Thirty, Forty, Fifty, Sixty, Seventy, Eighty, Ninety.
- So we are initializing an object of class numConWords as nw in the main class and we will call the function using dot operator.
- So as per number, the parameters will be passed to function as per the digit like if there are three-digit it will pass the number and Hundred and it will calculate and print the result same with the four-digit and so on.
Also read:
Leave a Reply