我正在尝试执行以下操作:
如果用户输入 1 到 100 之间的数字,则:
- 打印出从 1 到给定数字的每个序数。
下面的示例适用于输入值 25:
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
10th
11th
12th
13th
14th
15th
16th
17th
18th
19th
20th
21st
22nd
23rd
24th
25th
我不知道如何在不使用concat
的情况下添加:st, nd, rd, th
。
这是我的代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int userNum;
userNum = scnr.nextInt();
for (int i=1; i<=userNum; i++) {
System.out.println(i);
}
}
}
还有其他方法可以做到这一点吗?谢谢。
最佳答案
Java 中特殊的 String
连接运算符 (+
) 会自动将标量转换为字符串(当字符串位于左侧时)。你可以这样做:
System.out.println(""+i+getPostfix(i));
其中 getPostfix
将为给定整数(-st、-nd 等)返回适当的后缀。我将这个函数的实现留作练习。
关于java - 将 concat 与 int 一起使用? (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52936719/