Java program to print word for the given number
Converting a number to characters or to words as readable format in text will be done easily using arrays in java. Based on the given number we can write our logic. But here i am taking the number below to 10000. So we can complete our program easily. But sure, you will understand the logic. It is simple.using Fibonacci logic , using modulo operator and divider operator we can completer our program. This is important interview question and some of like, Reverse an array, matrix addition, matrix multiplication using arrays and prime number logic these are important for the java interviews.
In this program we have to create two arrays one is ones array with the words of one,two,three.....nineteen.
Then create another array with tens array contains ten,twenty,.....ninety.Then write the given logic to convert a number into character.
package com.javabynataraj; //http://javabynataraj.blogspot.com public class Num2String { public static void main(String[] args) { String ones[] = {"one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen",}; String tens[] = {"ten ","twenty ","thirty ","fourty ","fifty ","sixty ","seventy ","eighty ","ninety "}; int n = 7677; int i; String res=" "; if(n>1000){ i=n/1000; res=ones[i-1]+" thousand "; n=n%1000; } if(n>99 && n<1000){ i=n/100; res=res+ones[i-1]+" hundred "; n=n%100; } if(n>19 && n<100){ i=n/10; res=res+tens[i-1]; n=n%10; } if(n>0 && n<20){ res=res+ones[n-1]; } System.out.println(res); } }
Output:
Reference Books:
- A Programmer's Guide To Java SCJP Certification 3rd Edition
- Sun Certified Programmer For Java 6 Scjp
- Scjp Sun Certified Programmer For Java Platform
- SCJP Exam for J2SE 5