猿问

将 concat 与 int 一起使用?

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


如果用户输入了 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);

    }

  }

}

有没有其他方法可以做到这一点?谢谢。


慕工程0101907
浏览 243回答 3
3回答

慕无忌1623718

Java 中的特殊String连接运算符 (&nbsp;+) 会自动将标量转换为字符串(当字符串在左侧时)。你可以这样做:System.out.println(""+i+getPostfix(i));wheregetPostfix将为给定的整数(-st、-nd 等)返回一个合适的后缀。我将此功能的实现留作练习。

斯蒂芬大帝

你可以用 printf 做到这一点for (int i=1; i<=userNum; i++) {&nbsp; &nbsp; &nbsp;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 ");}

呼啦一阵风

你可以不使用 concat 来做到这一点。您可以使用模数检查 number -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 =&nbsp; &nbsp; &nbsp; &nbsp; Stream.of(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new SimpleEntry<>(1, "st"),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new SimpleEntry<>(2, "rd"),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new SimpleEntry<>(3, "nt"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));private static String getPostfix(int number) {&nbsp; &nbsp; if (Arrays.asList(11,12,13).contains(number)) return DEFAULT_POSTFIX;&nbsp; &nbsp; return Optional&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ofNullable(POSTFIX_MAP.get(number % 10))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .orElse(DEFAULT_POSTFIX);}public static void main(String[] args) {&nbsp; &nbsp; Scanner scanner = new Scanner(System.in);&nbsp; &nbsp; int userNum = scanner.nextInt();&nbsp; &nbsp; IntStream&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .rangeClosed(1, userNum)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .forEach(it -> System.out.println(it + getPostfix(it)));}}
随时随地看视频慕课网APP

相关分类

Java
我要回答