Beginners Programs :

Java Program To Print Ordinal Numbers | Java Porgrams

How to print ordinal numbers in Java – This specific article deals with the code for representing a user input number in its ordinal form using Java language.

Sample output along with suitable examples will be provided for a proper understanding of the java program for ordinal numbers converter.

  • The problem here is to represent a user-defined number in its ordinal form (Example: 42 as 42nd).
  • The input here is a number provided by the user, to change the number to ordinal java.
  • The output here is the ordinal form of the user-defined input number.
 

Output – 1:

Solution :

  1. In the class EndLetters, a static string array referenced by variable is initialized as a field variable.
  2. Since this array is declared as static, it does not belong to any object or instance of the class but belongs to the class itself.
  3. It is not a part of any method in the class and hence can be accessed by all the methods.
  4. The string values representing the end letters of an ordinal number (i.e.”st” | “nd” | “rd” | “th” date java) are stored in the array.
  5. In the main method, a new Scanner class object is initialized and a reference variable sc is set to represent the object. This class is used to take user input in Java.
  6. Scanner class is part of the java.util package and hence the import statement, in the beginning, is stated to import the functionality of the specified class.
  7. The next line prints a statement to the console instructing the user to enter a number.
  8. The .nextInt() method is called by the Scanner object sc. This method reads an int value input by a user and stores it to the int variable n.
  9. Within the print statement in the last line of the main method, the method ELON is called and is passed in as the argument for ordinal numbers converter.
  10.  In this method, the units place value of the input number is calculated and stored in variable k (n%10 finds the remainder when n is divided by 10) to determine the appropriate suffix for the number.
  11. A conditional statement returns the appropriate suffix by checking the value of and returning the suffix string value by obtaining it from the array s.
  12. This returned string suffix is printed out along with the number to represent the ordinal form of the user input number by the print statement in the main method.

 

 Output – 2:

  • Since the unit’s place number, in this case, is 5, the if condition in the ELON method is satisfied and the element at position 4 in the array (which is ‘th’) is returned. 455th is the correct representation of 455 in ordinal form.

 

Output – 3:

  • Since the unit’s place number, in this case, is 2, the else condition in the ELON method is satisfied and the element at position 2 in the array (which is ‘nd’) is returned. 122nd is the correct representation of 122 in ordinal form.