TransWikia.com

Java Scanner useDelimiter() Method

Stack Overflow Asked by MNH on December 14, 2020

    scanner.useDelimiter("\.|(?<=\d{2})");
    System.out.print("Enter dms: ");
    degrees = scanner.next();
    minutes = scanner.next();
    seconds = scanner.next();

An input of 36.5212 returns seconds = 1, not seconds = 12. How would I correct my scanner.useDelimeter method? Thank you!

One Answer

The problem is that the regex .|(?<=d{2}) is matching the position between the 1 and the 2, because at the position 36.521|2 (current position indicated by the | character), there are two digits to the left (the string 21).

You can change the regex to the following:

.|(?<=.d{2})

This way you enforce it, that the valid positions are only the . character itself or the position 36.52|12, where there is the positive look-behind of .dd (the string .52). The position 36.521|2 will not match anymore because the . character is missing between 5 and 2.

You can check the issue with your regex with the visualization from https://regex101.com/r/fL3kyA/1:

regex visualization

As you see by the pink bars, it finds three positions, even though you only want one.

Answered by Progman on December 14, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP