Java如何实现基数词转序数词?

来源:百度知道 编辑:UC知道 时间:2024/05/03 06:07:12
请实现一个函数String GetOrdinal(int number),输入一个整数,输出其数字简写的序数词(如11转换成11th),如下图所示。图片链接:

public class OrdinalTest {

public static String getOrdinal(int number) {
String tail = null;
if (number <= 0) {
return "number must > 0";
} else if (1 == number) {
return "First";
} else if (2 == number) {
return "Second";
} else if (number >= 20) {
int last = number % 10;
if (1 == last) {
tail = "st";
} else if (2 == last) {
tail = "nd";
} else if (3 == last) {
tail = "rd";
} else {
tail = "th";
}
} else {
tail = "th";
}
return number + tail;
}

public static void main(String[] args) {
for(int i = 1; i <= 31; i ++) {
System.out.println(OrdinalTest.getOrdinal(i));
}
}

}
//output
/*
First
Second
3th
4th
5th
6th
7t