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

后端 未结 12 1320
生来不讨喜
生来不讨喜 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

    I got a long, complicated one but easy to understand the concept

    private static void convertMe() {
    
        Scanner in = new Scanner(System.in);
        try {
            System.out.println("input a number to convert: ");
            int n = in.nextInt();
    
            String s = String.valueOf(n);
            //System.out.println(s);
    
            int len = s.length() - 1;
            if (len == 0){
                char lastChar = s.charAt(len);
                if (lastChar == '1'){
                    System.out.println(s + "st");
                } else if (lastChar == '2') {
                    System.out.println(s + "nd");
                } else if (lastChar == '3') {
                    System.out.println(s + "rd");
                } else {
                    System.out.println(s + "th");
                }
            } else if (len > 0){
                char lastChar = s.charAt(len);
                char preLastChar = s.charAt(len - 1);
                if (lastChar == '1' && preLastChar != '1'){ //not ...11
                    System.out.println(s + "st");
                } else if (lastChar == '2' && preLastChar != '1'){ //not ...12
                    System.out.println(s + "nd");
                } else if (lastChar == '3' && preLastChar != '1'){ //not ...13
                    System.out.println(s + "rd");
                } else {
                    System.out.println(s + "th");
                }
            }
    
    
        } catch(InputMismatchException exception){
            System.out.println("invalid input");
        }
    
    
    }
    

提交回复
热议问题