RitinMalhotra

Number in Words

Oct 29th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.01 KB | None | 0 0
  1. /**
  2.  * This program inputs a number greater than 99 and lesser than 1000 and returns the figure in words.
  3.  */
  4. import java.util.*;
  5. public class Number_In_Words
  6. {
  7.     static int[] getPos(int num) //Function to add the digits of the number entered into an int[] array.
  8.     {
  9.         int[] digits = new int[3]; //Stores [Hundreds, Tens, Units].
  10.         String a = Integer.toString(num);
  11.         int i,x;
  12.         for(i=0;i<a.length();i++)
  13.         {
  14.             x = Character.getNumericValue(a.charAt(i));
  15.             digits[i] = x;
  16.         }
  17.        
  18.         return digits;
  19.     }
  20.    
  21.     static String getWords(int[] digits)
  22.     {
  23.         String[] hundreds = {"", "One Hundred", "Two Hundred", "Three Hundred", "Four Hundred", "Five Hundred",
  24.                              "Six Hundred", "Seven Hundred", "Eight Hundred", "Nine Hundred"};
  25.        
  26.         String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
  27.        
  28.         String[] units = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
  29.        
  30.         String[] special = {"", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
  31.          
  32.         String number;
  33.        
  34.         if(digits[1] == 1 && digits[2] != 0) //Checking if the tens digit is >10 and <20 or not.
  35.         {
  36.             number = hundreds[digits[0]] + " and " + special[digits[2]];
  37.         }
  38.        
  39.         else if(digits[1] == 0 && digits[2] == 0) //Checking if the number is an exact hundred or not.
  40.         {
  41.             number = hundreds[digits[0]];
  42.         }
  43.         else
  44.         {
  45.             number = hundreds[digits[0]] + " and " + tens[digits[1]] + " " + units[digits[2]];
  46.         }
  47.        
  48.         return number;
  49.     }
  50.    
  51.     public static void main(String[] args)
  52.     {
  53.         Scanner sc = new Scanner(System.in);
  54.         System.out.println("Please enter a greater than 99 and lesser than 1000.");
  55.         int num = sc.nextInt();
  56.        
  57.         if(num < 100 || num > 999)
  58.         {
  59.             System.out.println("The number entered is out of range. Please try again.");
  60.         }
  61.        
  62.         else
  63.         {
  64.             int[] digits = getPos(num);
  65.             //display(digits);
  66.             String figure = getWords(digits);
  67.             System.out.println(figure);
  68.         }
  69.         sc.close();
  70.     }
  71. }
Add Comment
Please, Sign In to add comment