問題描述
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
這篇關于Java Scanner 類中的字符串格式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!