标准中的开关操作符

我想首先使用扫描仪输入从用户输入中获取 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 个案例?


凤凰求蛊
浏览 94回答 2
2回答

qq_遁去的一_1

本质上,您还应该首先检查右侧第二个数字是否为 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);

偶然的你

也许我们应该分别处理 4 到 20 号。您能检查一下这是否有效吗?if (abc > 3 && abc < 21) { // 4 to 20&nbsp; &nbsp; &nbsp; &nbsp; suffix = "th";}else {&nbsp; &nbsp; &nbsp; &nbsp; switch (abc % 10) { //get the last digit of the value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; suffix = "st";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case 2:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; suffix = "nd";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case 3:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; suffix = "rd";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; suffix = "th";&nbsp; &nbsp; &nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java