Java mysterious bug | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Java mysterious bug

Hi, I am currently studying java and I have this code which is supposed to help me understand how Scanner works. That's the code: Scanner scan = new Scanner("Name1$Name2$Name3$Name4"); scan.useDelimiter("

quot;); while (scan.hasNext()) { System.out.println(scan.next()); } scan.close(); (I imported the write packages... and coded this in the main function) For some peculiar reason, when I set the delimiter to be '
#x27;, the scanner ignores it completely, and when I go on to print the words essentially by order, it prints them all as one. Although when I set the delimiter to be something else, anything else such as ',' it behaves as expected and outputs: Name1 Name2 Name3 Name4 while when I use the '
#x27; as a delimiter it prints it all: Name1$Name2$Name3$Name4 I literally wasted I think 30 minutes or more trying to figure out what my mistake was - when I realized I just got unlucky :) - I managed to pick the only letter that the function doesn't recognize. I am interested to know why wouldn't the scanner identify the '
#x27; character as a delimiter. Anyone has an explanation? Thanks

28th Dec 2022, 1:25 PM
Alon Daniel
Alon Daniel - avatar
3 Answers
+ 5
It is quite complex i think. The „$“ character is used in regular expressions and this can be a issue for that. You could spend some time more for study the reference here: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#delimiter()
28th Dec 2022, 2:02 PM
JaScript
JaScript - avatar
+ 4
$ is ends with token in pattern ''$ blank end so return total string. If you want to take $ as delimiter then use escape sequence as scan.useDelimiter("\\
quot;);
28th Dec 2022, 2:46 PM
Jayakrishna 🇮🇳
+ 1
Ok, thanks!
28th Dec 2022, 4:14 PM
Alon Daniel
Alon Daniel - avatar