2 回答

TA貢獻1725條經驗 獲得超8個贊
本質上,您還應該首先檢查右側第二個數字是否為 1。要獲取右側第二個數字,請使用以下表達式:
number / 10 % 10
這/ 10使得從右邊算起的第二個數字成為第一個數字,% 10正如您所知,這就是如何獲得從右邊算起的第一個數字。
所以你的代碼看起來像這樣:
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);

TA貢獻1841條經驗 獲得超3個贊
也許我們應該分別處理 4 到 20 號。您能檢查一下這是否有效嗎?
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";
}
}
添加回答
舉報