For the parser class, I need to use parseProgram() to take a filename as a parameter, opens and read the contents of the file, and returns an ArrayList of Statement objects.
Since I am new to Java, I do not know where to start from.
I also like to know is the ParseLine method so far is right.


import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class Parser
	public static ArrayList<Statement> parseProgram(String filename)
	throws IOException

	// parseLine() takes a line from the input file and returns a Statement
	// object of the appropriate type.  This will be a handy method to call
	// within your parseProgram() method.
	private static Statement parseLine(String line)
		// Scanners can be used to break Strings into pieces, too!
		Scanner scanner = new Scanner(line);
		// The next() method returns the next word out of the String.
		// use the first word to decide on a statement type.
		String statementType = scanner.next();
		Statement statement = null;
		if (statementType.equals("LET"))
			char variable = scanner.next().charAt(0);
			int value = scanner.nextInt();

			statement = new LetStatement(variable, value);

		return statement;
6 Years
Discussion Span
Last Post by jon.kiparsky

It's okay as far as it goes, which isn't very far. Yes, you can use a scanner to tokenise a line, and yes this will take a statement like

LET a 10
and produce a LetStatement (a, 10)

But it'll have trouble with
LET a = 10 (if that's legal in your language - basic, is it?)

and it'll produce the same for
LET apples 10

LET aardvarks 10

Oh, and it won't produce a LetStatement at all for

let antelopes 10

so if your language allows lower-case, you might want to adjust for that.

Have you done any theory for this class? It's pretty involved stuff, and if you haven't dealt with that, writing a parser will be very difficult.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.