[英]Java Scanner does not ignore new lines (\n)
我知道默認情況下,掃描程序會跳過空格和換行符。 我的代碼有問題,因為我的掃描儀不會忽略“ \\ n”。
例如:輸入為“ this is \\ na test”。 期望的輸出應該是“這是一個測試”。
這是我到目前為止所做的:
Scanner scan = new Scanner(System.in);
String token = scan.nextLine();
String[] output = token.split("\\s+");
for (int i = 0; i < output.length; i++) {
if (hashmap.containsKey(output[i])) {
output[i] = hashmap.get(output[i]);
}
System.out.print(output[i]);
if (i != output.length - 1) {
System.out.print(" ");
}
nextLine()
忽略指定的定界符(由useDelimiter()
可選設置),並讀取到當前行的末尾。
由於輸入是兩行:
this is
a test.
僅返回第一行( this is
)。
然后,您將其拆分為空白,因此output
將包含[this, is]
。
由於不再使用掃描儀,因此將永遠不會讀取第二行( a test.
)。
本質上,您的標題是正確的: Java掃描程序不會忽略換行(\\ n)
當您調用nextLine()
時,它專門處理了換行符。
您不必使用Scanner
來執行此操作
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String result = in.lines().collect(Collectors.joining(" "));
或者,如果您真的想使用Scanner
這也應該有效
Scanner scanner = new Scanner(System.in);
Spliterator<String> si = Spliterators.spliteratorUnknownSize(scanner, Spliterator.ORDERED);
String result = StreamSupport.stream(si, false).collect(Collectors.joining(" "));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.