首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >第2,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4

第2,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4
EN

Stack Overflow用户
提问于 2019-10-04 13:13:15
回答 2查看 43关注 0票数 2

我想先使用扫描仪输入从用户的输入中获得一个3位数的数字。3位数字可以是001或999,但不能是000。然后我需要将这个数字打印在句子“*th person”中。假设3位数字是021,那么我希望它会打印“21人”。

代码语言:javascript
运行
复制
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个案例?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-10-04 14:15:49

实际上,您还应该首先检查右数第二位数是否为1。要获得右数第二位数,请使用以下表达式:

代码语言:javascript
运行
复制
number / 10 % 10

/ 10将右数第二位数设为第一位数,正如您所知道的,% 10是如何获得右数第一位数的。

因此,您的代码将如下所示:

代码语言:javascript
运行
复制
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);
票数 0
EN

Stack Overflow用户

发布于 2019-10-04 13:32:16

也许我们应该分开处理4号到20号。你能检查一下这个是否有效吗?

代码语言:javascript
运行
复制
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";
        }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58230283

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档