If a number 972 is entered through the keyboard, your program should print “Nine Seven Two”. Write a program such that it does this for any positive integer.

Below is a Java program that takes a positive integer as input and prints out each digit in words. This is achieved by first converting the integer to a string, then iterating over each character in the string and using a switch statement to print the corresponding word for each digit.

Convert digits to words

				
					import java.util.Scanner;

public class NumberToWords {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a positive integer: ");
        int number = scanner.nextInt();
        
        String numberString = Integer.toString(number);
        for (char digit : numberString.toCharArray()) {
            switch (digit) {
                case '0':
                    System.out.print("Zero ");
                    break;
                case '1':
                    System.out.print("One ");
                    break;
                case '2':
                    System.out.print("Two ");
                    break;
                case '3':
                    System.out.print("Three ");
                    break;
                case '4':
                    System.out.print("Four ");
                    break;
                case '5':
                    System.out.print("Five ");
                    break;
                case '6':
                    System.out.print("Six ");
                    break;
                case '7':
                    System.out.print("Seven ");
                    break;
                case '8':
                    System.out.print("Eight ");
                    break;
                case '9':
                    System.out.print("Nine ");
                    break;
                default:
                    System.out.print("Invalid digit ");
                    break;
            }
        }
    }
}

				
			
prime number

Explanation:

  1. Scanner Setup: We use Scanner to read the input from the user.
  2. Convert Number to String: The entered integer is converted to a string using Integer.toString(number).
  3. Iterate over Characters: We iterate over each character in the string representation of the number.
  4. Switch Statement: For each character, a switch statement is used to print the corresponding word. Each case corresponds to a digit from ‘0’ to ‘9’.
  5. Print Word: Depending on the digit, the appropriate word is printed with a space following it.

Sample Output:

If the user inputs 972, the program will output:

				
					Nine Seven Two 

				
			

This approach will work for any positive integer entered by the user.

Scroll to Top