views:

99

answers:

2

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

+2  A: 

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 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.

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 Strings that contain the data between all of the -s.

Here is a link to the String.split() documentation for your reading pleasure.

jjnguy
so there's no way around this but to use one Scanner which takes the full input, and another Scanner which parse the input?
starcorn
@klw, I will show you how I would do it in an edit.
jjnguy
@klw, you only need 1 `Scanner`.
jjnguy
won't String.split add whitespace to the String array as well? I have vague memory using split before.
starcorn
@klw, no. If you have the string `"A-B-C-D".split("-")` you get the array `["A","B","C","D"]`
jjnguy
+2  A: 

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.

stacker