我想先使用扫描仪输入从用户的输入中获得一个3位数的数字。3位数字可以是001或999,但不能是000。然后我需要将这个数字打印在句子“*th person”中。假设3位数字是021,那么我希望它会打印“21人”。
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个案例?
发布于 2019-10-04 14:15:49
实际上,您还应该首先检查右数第二位数是否为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);
发布于 2019-10-04 13:32:16
也许我们应该分开处理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";
}
}
https://stackoverflow.com/questions/58230283
复制相似问题