Is there a way in Java to convert an integer to its ordinal name?

后端 未结 12 1332
生来不讨喜
生来不讨喜 2020-11-27 15:12

I want to take an integer and get its ordinal, i.e.:

1 -> \"First\"
2 -> \"Second\"
3 -> \"Third\"
...
12条回答
  •  悲哀的现实
    2020-11-27 15:41

    Best and Simple way, Here we go:

    import java.util.*;
    public class Numbers 
    {
        public final static String print(int num)
        {
            num = num%10;
            String str = "";
            switch(num)
            {
            case 1:     
                str = "st";
                break;
            case 2:     
                str = "nd";
                break;
            case 3:     
                str = "rd";
                break;
            default: 
                str = "th";             
            }
            return str;
        }
    
        public static void main(String[] args) 
        {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int number = sc.nextInt();
            System.out.print(number + print(number));
        }
    }
    

提交回复
热议问题