Java Scanner 类中的字符串格式

2022-01-12 00:00:00 string formatting java
Scanner i=new Scanner(System.in);

System.out.println("Enter an integer: ");
int in=i.nextInt();

System.out.println("Enter an floating point number: ");
double d=i.nextDouble();

System.out.println("Enter a string: ");
String str=i.next();

System.out.printf("%s%n,Sum of%2d and %.2f is %.2f%n",str,in ,d,in+d);

我的问题是格式化我通过扫描仪输入的字符串.我试图输入结果是",但 printf() 似乎只看到字符串的结果"部分,那么空格的命令是什么?谢谢

My problem is with formatting the String I enter through Scanner. I was trying to enter "Result is", but printf() seems to see only the "Result" part of string, so what is the command for blank space? thx

推荐答案

有几种可能的解决方案,但我相信以下内容会为您提供与其他输入一致的行为:

There are several possible solutions, but I believe the following will give you consistent behavior with the other inputs:

System.out.println("Enter an floating point number: ");
double d = i.nextDouble();
i.skip("((?<!\R)\s)*"); // skip whitespace, stopping after any newline

System.out.println("Enter a string: ");
String str = i.nextLine();

如果需要,这种方法可以让您在一行中输入所有输入.

This approach would allow you to enter all the inputs on a single line, if so desired.

例如:

1 1.2 结果是

但是,如果您真的打算让您的用户在每次输入后按 Enter,那么使用 Scanner 的 nextLine() 方法读取所有输入,然后根据需要进行解析(使用 Integer.parseInt 等).

However if you really intend for your users to press Enter after every input, then it would be most consistent to read all the inputs with Scanner's nextLine() method, then parse as needed (using Integer.parseInt, etc).

Java 9

由于 Java 9 中的一个错误,必须在换行符匹配器 R 周围添加原子分组 (?> ... ).有关详细信息,请参阅错误报告 JDK-8176983.

Due to a bug in Java 9, the atomic grouping (?> ... ) must be added around the linebreak matcher R. See bug report JDK-8176983 for details.

i.skip("((?<!(?>\R))\s)*"); // skip whitespace, stopping after any newline
                              // Compatibility Note: Java 9 safe use of R

如果用于 Java 8,此代码也可以正常工作并且不会导致任何问题,因此实际上我建议您在代码中使用此解决方法版本,只是为了安全起见(例如,如果有人可能复制/粘贴或设置目标到不同的 JDK).

This code will also work fine and not cause any problems if used for Java 8, so actually I recommend you use this workaround version in your code just to be on the safe side (e.g. if someone may copy/paste or set target to a different JDK).

Java 7 及更早版本

换行符匹配器 R 在 Java-8 或更高版本中可用.在该版本之前,您必须使用等效"模式 u000Du000A|[u000Au000Bu000Cu000Du0085u2028u2029] 但是作为真正的等效模式它实际上必须包含在原子分组 (?> ... ) 中.有关详细信息,请参阅文档错误报告 JDK-8176029.p>

The linebreak matcher R is available in Java-8 or later. Prior to that version, you would have to use the "equivalent" pattern u000Du000A|[u000Au000Bu000Cu000Du0085u2028u2029] however to work as a true equivalent it actually must be wrapped in the atomic grouping (?> ... ). See documentation bug report JDK-8176029 for details.

i.skip("((?<!(?>\u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]))\s)*"); // skip whitespace, stopping after any newline

相关文章