Display Number in Words ISC Computer Science 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.util.Scanner;
class Words{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter natural number < 1000");
int num = Integer.parseInt(in.nextLine());
if(num >= 1000){
System.out.println("OUT OF RANGE");
return;
}
int hundreds = num / 100;
int tens = (num % 100);
int ones = (num % 100) % 10;
String w[] = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"};
String tn[] = {"ZERO", "TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"};
if(hundreds > 0)
System.out.print(w[hundreds] + " HUNDRED ");
if(tens > 0 && tens < 20)
System.out.print(w[tens] + " ");
else if(tens > 1)
System.out.print(tn[tens / 10] + " ");
if(ones > 0 && tens > 19)
System.out.println(w[ones]);
}
}
class Words{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter natural number < 1000");
int num = Integer.parseInt(in.nextLine());
if(num >= 1000){
System.out.println("OUT OF RANGE");
return;
}
int hundreds = num / 100;
int tens = (num % 100);
int ones = (num % 100) % 10;
String w[] = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"};
String tn[] = {"ZERO", "TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"};
if(hundreds > 0)
System.out.print(w[hundreds] + " HUNDRED ");
if(tens > 0 && tens < 20)
System.out.print(w[tens] + " ");
else if(tens > 1)
System.out.print(tn[tens / 10] + " ");
if(ones > 0 && tens > 19)
System.out.println(w[ones]);
}
}
Comments
Post a Comment