Java Program convert number to words

Here we write a Java program convert number to words.we have perform following step :-

  • First we create the Scanner class object to pass user input.
  • From sc.nextInt() method take user input as Integer type and store in userNumber variable.
  • Inside first if condition we check user input should be less than 1 and greater than 100, if it is then print wrong number.
  • Inside else if condition we check user input should be between 1 to 19,then print number to words.
  • Inside second else if condition we check user input should be between 20 to 99, then print number to words.
  • Here we get the divide the number by 10 and store the divided in digit1.now pass this digit1 in array type string str1.
  • Now we modulo the number by 10 and store in digit2,after that pass this digit2 in array type string str2.
  • After that all number is comparing with string array index value and print the number in words.

				
					import java.util.Scanner;

public class A {
	public static void main(String[] args) {

		int userNumber, digit1, digit2;
		Scanner sc = new Scanner(System.in);

		String str1[] = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "nenety" };
		String str2[] = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
				"twelve", "thirteen", "fourteen", "fifteen", "sixteen", "eighteen", "ninteen" };
		
		System.out.println("Enter the user number between 1 to 99");
		userNumber = sc.nextInt();

		if ((userNumber < 1) || (userNumber > 100)) {
			System.out.println("wrong number");
		} else if ((userNumber >= 1) && (userNumber <= 19)) {
			System.out.println("Number in words :- " + str2[userNumber]);
		} else if ((userNumber >= 20) && (userNumber <= 99)) {
			digit1 = userNumber / 10;
			digit2 = userNumber % 10;
			System.out.println("print number to words :- " + str1[digit1] + " " + str2[digit2]);
		}
	}
}
				
			

Output :-
Enter the user number between 1 to 99
56
print number to words :- fifty six