java 扫描仪,使用分隔符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3493230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scanner, useDelimiter
提问by starcorn
I encounter some problem when using useDelimiter from the Scanner class.
使用 Scanner 类中的 useDelimiter 时遇到一些问题。
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
AB
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
但是,如果我没有让用户输入数据,而是向扫描仪插入一个字符串,则代码将起作用。它的原因是什么,我该如何解决?我不想使用 StringTokenzier
回答by jjnguy
If the Scannerdidn't wait for you to enter another -then it would erroneously assume that you were done typing input.
如果Scanner没有等待您输入另一个,-那么它会错误地认为您已完成输入。
What I mean is, the Scannermust wait for you to enter a -because it has no way to know the length of the next input.
我的意思是,Scanner必须等你输入a,-因为它无法知道下一个输入的长度。
So, if a user wanted to type A-B-CDEand 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 ])
因此,如果用户想要输入A-B-CDE而您在 处停下C来喝一口咖啡,则不会得到正确的输入。(你期望[ A, B, CDE ]但它会得到[ A, B, C ])
When you pass it in a full String, Scannerknows where the end of the input is, and doesn't need to wait for another delimiter.
当您以 full 形式传递它时String,Scanner知道输入的结尾在哪里,并且不需要等待另一个分隔符。
How I would do it follows:
我将如何做如下:
Scanner stdin = new Scanner(System.in);
String input = stdin.nextLine();
String[] splitInput = input.split("-", -1);
You will now have an array of Stringsthat contain the data between all of the -s.
您现在将拥有一个Strings包含所有-s之间数据的数组。
Here is a link to the String.split()documentation for your reading pleasure.
回答by stacker
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.
您可以使用替代分隔符字符串useDelimiter( "-|\n" );它适用于 String 参数以及从System.in. 在 System.in 的情况下,这需要您在行尾按 Enter。
回答by starcorn
How I would do it follows:
我将如何做如下:
Scanner stdin = new Scanner(System.in);
String s = stdin.nextLine();
String[] splitInput = s.split("-", -1);
You will now have an array of Stringsthat contain the data between all of the -s.
您现在将拥有一个Strings包含所有-s之间数据的数组。

