Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将concat与int一起使用?(爪哇)_Java_Concat - Fatal编程技术网

Java 将concat与int一起使用?(爪哇)

Java 将concat与int一起使用?(爪哇),java,concat,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 如果不使用concat,我想不出如何添加:st、nd、rd、th 这是我的密码: import java.util.Scanner;

我正在努力做到以下几点:

如果用户输入的数字介于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);
    }
  }
}
import java.util.Scanner;
公共班机{
公共静态void main(字符串[]args){
扫描仪scnr=新扫描仪(System.in);
int userNum;
userNum=scnr.nextInt();

对于(int i=1;i,Java中的特殊
String
concatation操作符(
++
)将自动将标量转换为字符串(当字符串位于左侧时)。您可以执行以下操作:

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

其中,
getPostfix
将为给定的整数(-st,-nd等)返回一个合适的后缀。我将此函数的实现留作练习。

您可以不使用concat来完成此操作。您可以检查数字-st-nd-rd是否带模 (%10)

import java.util.*;
导入java.util.AbstractMap.SimpleEntry;
导入java.util.stream.collector;
导入java.util.stream.IntStream;
导入java.util.stream.stream;
公共班机{
私有静态最终字符串默认值\u POSTFIX=“th”;
私有静态最终映射后缀\映射=
溪流(
新单纯形(1,“st”),
新单纯形(2,“rd”),
新单纯形(3,“nt”))
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
私有静态字符串getPostfix(整数){
if(Arrays.asList(11,12,13).contains(number))返回默认后缀;
返回可选
.ofNullable(POSTFIX\u MAP.get(数字%10))
.orElse(默认后缀);
}
公共静态void main(字符串[]args){
扫描仪=新的扫描仪(System.in);
int userNum=scanner.nextInt();
IntStream
.rangeClosed(1,userNum)
.forEach(it->System.out.println(it+getPostfix(it));
}

}

您可以使用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 ");
}
for(inti=1;i19?“st”:i%10==2&&i>19?“nd”:i%10==3&&i>19?“rd”:“th”);
}

你对concat有什么反对意见?可能与System.out.print(i);System.out.println(theSuffix);
重复。我可以在整数上使用concat吗?你会想要一个字符串。它不是11号,它是11号。12号、13号等相同。可能与111号、212号、413号等相同,但它的数字在1到100之间(从问题开始)这非常接近,但结果是11、12和13分别是第11、12和13位。这是一个快速的答案,您可以详细说明其余部分。为了方便起见,我更新了代码:)
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 ");
}