java - 将 concat 与 int 一起使用? (java)

标签 java concatenation

我正在尝试执行以下操作:

如果用户输入 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/

相关文章:

java - 传递 JSON 对象

java - 将多个模块的 Javadoc 合并到一个集合中

concatenation - 连接动态结构的字段

python - 连接两个一维 NumPy 数组

java - 如何在 GWT 中获取一年中的星期数

java - Hibernate:使用executeUpdate()批量删除不会清除一级缓存

php - 对同一 PHP 脚本的并行请求导致第二次长时间延迟

mysql - 我可以将多个 MySQL 行连接到一个字段中吗?

java - 使用 System.out.println() 打印对象时串联问题;

javadoc:如何使用它在 Window 7 上记录一个 java 文件?