Number to Words ISC 2011 Practical

Write a program to input a natural number less than 1000 and display it in words.

Test your program for the given sample data and some random data.

INPUT: 29
OUTPUT: TWENTY NINE

INPUT: 17001
OUTPUT: OUT OF RANGE

INPUT: 119
OUTPUT: ONE HUNDRED AND NINETEEN

INPUT: 500
OUTPUT: FIVE HUNDRED

import java.io.*;
class Natural{
public static void main(String[] args)throws IOException{
System.out.print("Natural number less than 1000: ");
int n = Integer.parseInt(br.readLine());
if(n < 1 || n > 999){
System.out.println("OUT OF RANGE");
return;
}
String ones[] = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
String teens[] = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
String tens[] = {"", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
String words = new String();
boolean threeDigit = n > 99;
if(n > 99){
int d = n / 100;
n %= 100;
words += ones[d] + " hundred ";
}
if(n > 19 || n == 10){
int d = n / 10;
n %= 10;
words += tens[d] + " ";
}
if(n > 10){
int d = n % 10;
n /= 10;
if(threeDigit)
words += "and " + teens[d];
else
words += teens[d];
}
else if(n > 0){
if(threeDigit)
words += "and " + ones[n];
else
words += ones[n];
}
words = words.toUpperCase();
System.out.println(words);
}
}