我想取一个整数并获取其序数,即:

1 -> "First"
2 -> "Second"
3 -> "Third"
...

最佳答案

如果您对1st2nd3rd等没问题,以下是一些可以正确处理任何整数的简单代码:

public static String ordinal(int i) {
    String[] suffixes = new String[] { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
    switch (i % 100) {
    case 11:
    case 12:
    case 13:
        return i + "th";
    default:
        return i + suffixes[i % 10];

    }
}
以下是一些针对极端情况的测试:
public static void main(String[] args) {
    int[] tests = {0, 1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 100, 101, 102, 103, 104, 111, 112, 113, 114, 1000};
    for (int test : tests) {
        System.out.println(ordinal(test));
    }
}
输出:
0th
1st
2nd
3rd
4th
5th
10th
11th
12th
13th
14th
20th
21st
22nd
23rd
24th
100th
101st
102nd
103rd
104th
111th
112th
113th
114th
1000th

关于java - Java中是否可以将整数转换为序数名称?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6810336/

10-09 16:38
查看更多