I've many question like this before, but every solution I've found involves the usage of indexOf. Just like here.
Well, I'm implementing a recursive descent parser, and after execution each production I've to print the production, something like "A = B 'token' (value of token) C". The problem arises when productions have many other productions and tokens, if I print it in the begining of the production I don't have the value of every token, if I print it in the end the final list of productions will be in an incorrect order.
So I'm doing something like this:
String s="";
productions.add(s);
A();
getToken();
B();
s=("A 'token' B");
You can see that in the method A() I might have something like that too, so I will be addind many s="" to the list, thus indexOf wont work. Currently I'm doing this:
String s="";
s+= productions.size();
productions.add(s);
A();
getToken();
B();
s=("A 'token' B");
But I don't find this solution anyhow elegant. There is a better way to do that?
Here is an example of what I'm trying to do, note that it won't work because you need a lexical analyser that implements the nextToken method
public class parser {
ArrayList<String> productions = new ArrayList<>();
void S(){
//S = A '*' B
String s="";
productions.add(s);
A();
nextToken();
B();
s="S = A '*' B"
printProductions();
}
void A(){
//A = 'ctn' | B
String s="";
productions.add(s);
if(!currentTk=ctn){
s="A = B
B();
}else{
s="A = 'ctn'
}
}
void B(){
//B = 'ctn' '+' 'ctn'
String s="";
productions.add(s);
if(currentTk=ctn){
nextToken();
if(currentTk=ctn){
if(currentTk=ctn){
nextToken();
s= "'ctn' '+' 'ctn'"
}
}
}
}
}
A(),B()andgetToken()methods, ignoring any results. It would be much easier to help you if you'd post a minimal reproducible example.