Ques 10

Pg 126
mail@pastecode.io avatar
unknown
java
a year ago
1.5 kB
3
Indexable
Never
import java.util.Scanner;

public class NumberToWords {
    private static final String[] units = {
            "", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN",
            "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"
    };

    private static final String[] tens = {
            "", "", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"
    };

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a natural number less than 1000: ");
        int number = scanner.nextInt();
        scanner.close();

        if (number < 0 || number >= 1000) {
            System.out.println("Invalid input. Number must be between 0 and 999.");
        } else if (number == 0) {
            System.out.println("ZERO");
        } else {
            String words = convertNumberToWords(number);
            System.out.println(words);
        }
    }

public static String convertNumberToWords(int number) {
    if (number < 20) {
        return units[number];
    } else if (number < 100) {
        return tens[number / 10] + " " + units[number % 10];
    } else {
        if (number % 100 != 0) {
            return units[number / 100] + " HUNDRED AND " + convertNumberToWords(number % 100);
        } else {
            return units[number / 100] + " HUNDRED";
        }
    }
}

}