hehexd hehexd - 3 years ago 147
Java Question

How to use scanner to read a recursive grammar

Is there a way to use the Scanner class to read a grammar?

Let's say we have this file.

Is there any logical way that makes it possible for me to create a class object and also fill it's attributes and operations.
I tried using the useDelimiter(";"), but returns the full class without separating it well, should i reset? what's the practical way to treat this.

name: String
nb_players() : Integer,
trainer() : String

name : String

I have already created the objects, for example my class Class has these attributes

public final String Identifier;
public final Class_Content class_content;

class_content contains the attributes and operations( a recursive way of doing things)

Answer Source

Is there a way to use the Scanner class to read a grammar?

You almost certainly do not want to read a grammar. It is most likely1 that you want to read a file that conforms to a grammar.

You cannot read text conforming to an inherently recursive grammar with a simple call or calls to java.util.Scanner. You need to construct a parser.

The example that you have given doesn't look like it needs a recursive grammar to describe it. However, I think writing or generating a parser is probably the best solution.

If you want to write one, there are tutorials / examples on the web:

If you want to generate one, you can learn and use a parser generator tool such as JavaCC or AntLR.

1 - But in the event that you do want to actually read a grammar (G), then the problem is basically the same. The grammar must be expressed in some language, and that language has a grammar (GG). You need to read / parse the your grammar G using a parser of GG. For instance, EBNF notation has a simple grammar, so to read a grammar expressed in EBNF you need a parser for EBNF.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download