2

I want to get a 3 digit number from the user's input using scanner input first. The 3 digits number can be 001 or 999 but not 000. Then I need to print this number in a sentence "***th person". Let's say if the 3 digit number is 021 then I expect it will print "21st person".

import java.util.Scanner;
public class Main
{
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a value ");
    int abc = input.nextInt();
    String suffix = "";
    if(abc==000){
    System.out.println("invalid input");
    }
    switch(abc%10){ //get the last digit of the value
         case 1: suffix = "st";break;
         case 2: suffix = "nd";break;
         case 3: suffix = "rd";break;
         default: suffix = "th";
    }
    System.out.println(abc+suffix);
    }
}

How can I change my code such that the program will check 11th 12th 13th 111th cases?

Brian Wu
  • 23
  • 2

2 Answers2

0

May be we should handle number 4 to 20 separately. Can you please check if this works?

if (abc > 3 && abc < 21) { // 4 to 20
        suffix = "th";
}
else {
        switch (abc % 10) { //get the last digit of the value
            case 1:
                suffix = "st";
                break;
            case 2:
                suffix = "nd";
                break;
            case 3:
                suffix = "rd";
                break;
            default:
                suffix = "th";
        }
}
Atul Kumbhar
  • 1,073
  • 16
  • 26
0

Essentially, you also should first check whether the second digit from the right is 1. To get the second digit from the right, use this expression:

number / 10 % 10

The / 10 makes the second digit from the right the first digit, and % 10 is, as you know, how you get the first digit from the right.

So your code would look like this:

if (number / 10 % 10 == 1) { // check second digit from the right first
    suffix = "th";
} else { // if it's not 1, do the switch.
    switch(abc%10){
         case 1: suffix = "st";break;
         case 2: suffix = "nd";break;
         case 3: suffix = "rd";break;
         default: suffix = "th";
    }
}
System.out.println(abc+suffix);
Sweeper
  • 213,210
  • 22
  • 193
  • 313