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

时间:2018-10-22 19:43:45

标签: java concat

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

如果用户输入的数字介于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

我不知道如何在不使用 st, nd, rd, th 的情况下添加concat

这是我的代码:

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);
    }
  }
}

还有另一种方法吗?谢谢。

3 个答案:

答案 0 :(得分:1)

Java中特殊的String合并运算符(+)将标量自动转换为字符串(当字符串在左侧时)。您可以执行以下操作:

System.out.println(""+i+getPostfix(i));

其中getPostfix将为给定的整数(-st,-nd等)返回适当的后缀。我将实现该功能作为练习。

答案 1 :(得分:1)

您可以使用printf

for (int i=1; i<=userNum; i++) {
     System.out.printf("%d%s\n",i,i%10==1 && i>19 ? "st " : i%10==2 && i>19 ? "nd " : i%10==3 && i>19 ? "rd " : "th ");
}

答案 2 :(得分:0)

您可以在不使用concat的情况下进行操作。您可以检查数字-st -nd -rd是否具有模数 (%10)

import java.util.*;
import java.util.AbstractMap.SimpleEntry;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Main {

private static final String DEFAULT_POSTFIX = "th";
private static final Map<Integer, String> POSTFIX_MAP =
        Stream.of(
                new SimpleEntry<>(1, "st"),
                new SimpleEntry<>(2, "rd"),
                new SimpleEntry<>(3, "nt"))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

private static String getPostfix(int number) {
    if (Arrays.asList(11,12,13).contains(number)) return DEFAULT_POSTFIX;
    return Optional
            .ofNullable(POSTFIX_MAP.get(number % 10))
            .orElse(DEFAULT_POSTFIX);
}

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int userNum = scanner.nextInt();
    IntStream
            .rangeClosed(1, userNum)
            .forEach(it -> System.out.println(it + getPostfix(it)));
}

}

相关问题