[英]Cannot split input from `Scanner`
String command = scanner.next();
String[] split = command.split(" ");
System.out.println(split.length);
您好,任何人都知道為什么當我插入"ab c defghi"
時它會返回長度 1 嗎?
next()
讀取輸入直到空格( " "
),因此變量command
將是"a"
而不是"ab c defghi"
您應該使用nextLine()
來讀取輸入,包括字母之間的空格:
Scanner scanner = new Scanner(System.in);
String command = scanner.nextLine();
String[] split = command.split(" ");
System.out.println(split.length);
有關更多信息,請查看doc 。
您只檢索行中的 a 而不是整行 use String command =scanner.nextLine(); 反而。
next()
和nextLine()
方法是 Scanner 用於獲取字符串輸入的兩種不同方法。
next()
只能讀取輸入直到空格。 它無法讀取以空格分隔的兩個單詞。 此外, next()
在讀取輸入后將 cursor 放在同一行。
nextLine()
讀取輸入,包括單詞之間的空格(也就是說,它讀取到行尾 \n)。 讀取輸入后, nextLine()
將 cursor 定位在下一行。
所以在這里你應該使用nextLine()
而不是next()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.