Olivier Grégoire Olivier Grégoire - 1 month ago 23
Java Question

Dice notation (recursive descent parsing implementation): a scanner without delimiter

I would like to build a recursive descent parsing implementation of the dice notation using the java Scanner if possible. I've previously opened a question about it , but it seemed that I had my requirements way too simplified. So I'm presenting here the request in its globality.

I really hope that this is feasible with the class java.util.Scanner, but if needed I will write my own scanner. I would like to avoid this one right now.

expression = { whitespace } , [ plusminus ] , roll , { plusminus , ( roll | number , { whitespace } ) } ;
roll = [ number ] , ( "d" | "D" ) , ( number | "%") , [ "-" ( "L" | "H" ) ] , { whitespace } ;
plusminus = ( "+" | "-" ) , { whitespace } ;
number = nonzerodigit , { digit } ;
digit = nonzero digit | "0" ;
nonzerodigit = "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
whitespace = ? Java definition of a whitespace ? ;


So in fact, I've tried to write the following code:

Scanner s = new Scanner("1d6");
if (s.hasNextInt()) {
s.nextInt();
} else {
throw new java.text.ParseException();
}


But obviously it keeps failing.

Also as suggested in the previous question, I've tried the findWithinHorizon methods but it really finds the next pattern and doesn't check from where I am. So I can't "pushback" the string if it is not what I need...

So any suggestion on how I should use java.util.Scanner in this context? Or maybe I have to write my own scanner?

Answer

You should not use java.util.Scanner. Take a look at the design of JParsec.