Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * This program inputs a number greater than 99 and lesser than 1000 and returns the figure in words.
- */
- import java.util.*;
- public class Number_In_Words
- {
- static int[] getPos(int num) //Function to add the digits of the number entered into an int[] array.
- {
- int[] digits = new int[3]; //Stores [Hundreds, Tens, Units].
- String a = Integer.toString(num);
- int i,x;
- for(i=0;i<a.length();i++)
- {
- x = Character.getNumericValue(a.charAt(i));
- digits[i] = x;
- }
- return digits;
- }
- static String getWords(int[] digits)
- {
- String[] hundreds = {"", "One Hundred", "Two Hundred", "Three Hundred", "Four Hundred", "Five Hundred",
- "Six Hundred", "Seven Hundred", "Eight Hundred", "Nine Hundred"};
- String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
- String[] units = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
- String[] special = {"", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
- String number;
- if(digits[1] == 1 && digits[2] != 0) //Checking if the tens digit is >10 and <20 or not.
- {
- number = hundreds[digits[0]] + " and " + special[digits[2]];
- }
- else if(digits[1] == 0 && digits[2] == 0) //Checking if the number is an exact hundred or not.
- {
- number = hundreds[digits[0]];
- }
- else
- {
- number = hundreds[digits[0]] + " and " + tens[digits[1]] + " " + units[digits[2]];
- }
- return number;
- }
- public static void main(String[] args)
- {
- Scanner sc = new Scanner(System.in);
- System.out.println("Please enter a greater than 99 and lesser than 1000.");
- int num = sc.nextInt();
- if(num < 100 || num > 999)
- {
- System.out.println("The number entered is out of range. Please try again.");
- }
- else
- {
- int[] digits = getPos(num);
- //display(digits);
- String figure = getWords(digits);
- System.out.println(figure);
- }
- sc.close();
- }
- }
Add Comment
Please, Sign In to add comment