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

Related Questions

How do I debug SwiftUI AttributeGraph cycle warnings?

5  Asked on December 30, 2021 by sindre-sorhus

       

RTD client in Python

1  Asked on December 30, 2021 by hunk

     

How to remove mongo specific fields from result (NodeJS, Mongoose)

5  Asked on December 30, 2021 by ararat-harutyunyan

     

Problem with ionic framework How can I solve?

0  Asked on December 30, 2021 by scar-fuentes

         

Random Forest Output

0  Asked on December 30, 2021 by charles-biwer

     

How to shift range of cells to unify values in rows

2  Asked on December 30, 2021 by jozef

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir