亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

標準中的開關操作符

標準中的開關操作符

鳳凰求蠱 2023-09-27 10:31:17
我想首先使用掃描儀輸入從用戶輸入中獲取 3 位數字。3位數字可以是001或999,但不能是000。然后我需要在句子“***th person”中打印這個數字。假設如果 3 位數字是 021 那么我預計它會打印“21st person”。import java.util.Scanner;public class Main{    public static void main(String[] args) {    Scanner input = new Scanner(System.in);    System.out.print("Enter a value ");    int abc = input.nextInt();    String suffix = "";    if(abc==000){    System.out.println("invalid input");    }    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";    }    System.out.println(abc+suffix);    }}我如何更改我的代碼,以便程序檢查第 11、12、13、111 個案例?
查看完整描述

2 回答

?
qq_遁去的一_1

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);


查看完整回答
反對 回復 2023-09-27
?
偶然的你

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";

        }

}


查看完整回答
反對 回復 2023-09-27
  • 2 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號