扫描仪,使用Delimiter [英] Scanner, useDelimiter
问题描述
我在使用Scanner类中的useDelimiter时遇到一些问题。
I encounter some problem when using useDelimiter from the Scanner class.
Scanner sc = new Scanner(System.in).useDelimiter("-");
while(sc.hasNext())
{
System.out.println(sc.next());
}
如果我有这个输入
ABC
A-B-C
输出将
AB
A B
并等到我输入另一个 - 表示打印出来最后一个字符
and wait until I type in another "-" for it to print out the last character
但是,如果我没有用户输入数据,而是将字符串插入扫描程序,则代码将起作用。它是什么原因,我该如何解决?我不想使用StringTokenzier
However if I instead of having user input data, and insert a String to the Scanner instead the code will work. What's the reason for it, and how do I fix it? I don't want to use StringTokenzier
推荐答案
如果扫描仪
没有等你输入另一个 -
然后它会错误地认为你输入了输入。
If the Scanner
didn't wait for you to enter another -
then it would erroneously assume that you were done typing input.
我的意思是,扫描仪
必须等待您输入 -
因为它无法知道下一个输入的长度。
What I mean is, the Scanner
must wait for you to enter a -
because it has no way to know the length of the next input.
因此,如果用户想要输入 AB -CDE
你停下来在 C
喝了一口咖啡,它得不到正确的输入。 (你期望 [A,B,CDE]
但它会得到 [A,B,C]
)
So, if a user wanted to type A-B-CDE
and you stopped to take a sip of coffee at C
, it woud not get the correct input. (You expect [ A, B, CDE ]
but it would get [ A, B, C ]
)
当你以完整的字符串
传递它时,扫描器
知道输入的结尾是,并且不需要等待另一个分隔符。
When you pass it in a full String
, Scanner
knows where the end of the input is, and doesn't need to wait for another delimiter.
我将如何做到:
Scanner stdin = new Scanner(System.in);
String input = stdin.nextLine();
String[] splitInput = input.split("-", -1);
现在你将有一个数组的数组
包含所有 -
之间的数据。
You will now have an array of Strings
that contain the data between all of the -
s.
这是<$的链接c $ c> String.split()您的阅读乐趣文档。
Here is a link to the String.split()
documentation for your reading pleasure.
这篇关于扫描仪,使用Delimiter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!