扫描仪,使用分隔符
使用 Scanner 类中的 useDelimiter 时遇到一些问题。
Scanner sc = new Scanner(System.in).useDelimiter("-");
while(sc.hasNext())
{
System.out.println(sc.next());
}
如果我有这个输入
ABC
输出将是
A B
并等到我输入另一个“-”,让它打印出最后一个字符
但是,如果我不让用户输入数据,而是将字符串插入到扫描仪中,则代码将起作用。这是什么原因,我该如何解决?我不想使用 StringTokenzier
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());
}
if I have this input
A-B-C
the output will be
A B
and wait until I type in another "-" for it to print out the last character
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果
扫描仪
没有等待您输入另一个-
,那么它会错误地认为您已完成输入。我的意思是,
Scanner
必须等待您输入-
,因为它无法知道下一个输入的长度。因此,如果用户想要输入
AB-CDE
,而您在C
停下来喝了一口咖啡,则不会获得正确的输入。 (您期望[ A, B, CDE ]
但它会得到[ A, B, C ]
)当您以完整的
String
形式传递它时>,Scanner
知道输入的结尾在哪里,并且不需要等待另一个分隔符。我将如何做到这一点如下:
您现在将拥有一个
Strings
数组,其中包含所有-
之间的数据。这里是
String.split()
文档的链接,供您阅读。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.So, if a user wanted to type
A-B-CDE
and you stopped to take a sip of coffee atC
, 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.How I would do it follows:
You will now have an array of
Strings
that contain the data between all of the-
s.Here is a link to the
String.split()
documentation for your reading pleasure.您可以使用替代分隔符字符串
useDelimiter( "-|\n" );
它可以使用 String 参数以及从 System.in 读取。
如果是 System.in,则需要您在行尾按 Enter 键。
You could use an alternative delimiter string
useDelimiter( "-|\n" );
It works with a String argument as well as by reading from
System.in
.In case of System.in this requires you to press enter at the end of the line.
我将如何做到这一点如下:
您现在将拥有一个
Strings
数组,其中包含所有-
之间的数据。How I would do it follows:
You will now have an array of
Strings
that contain the data between all of the-
s.