简体   繁体   中英

How do I use BufferedReader to put lines in an ArrayList and then execute them?

I'm attempting to write a program that will execute and produce an output of simplified programming language statements from a file. There are several lines in the file that will give statements like variable = expression, PRINT variable, GOTO 'x line', IF variable IS value THEN .... etc. A line that says END is the last line and is supposed to stop the program.

I'm using blanks as the delimiters, and know that I will need to use a BufferedReader and then tokenizer to split up these lines. What I'm struggling with is how to store all of these statements/variables once they're split? Would parallel ArrayLists be a good way to do this? How do I read each variable and expression separately and evaluate it? This is what I have so far:

public void processProgram() {
    String fileName = getFileName();
    if(fileName != null)
        processProgram();
    String line = null;
    ArrayList<String> name = new ArrayList<String>();
    ArrayList<Integer> value = new ArrayList<Integer>();
    try (BufferedReader br = new BufferedReader(new FileReader(getFileName())))
    {

        while((line = br.readLine()) != null){
            name.add(line);
        }
    }  catch (IOException e) {
        e.printStackTrace();
    } 

    StringTokenizer tok = new StringTokenizer(line);
    while (tok.hasMoreTokens()) {
        String token = tok.nextToken(" ");

    }


}

I'm a total beginner so any direction would be amazing.

A simple way to do this would be to have a setup which is something like the following:

List<String> lines; // from the file
int currentIndex;   // the "instruction pointer"

You could use something like a Map<String, Double> vars; to store your variables in. (See Map tutorial .)

And then have a method which is something like this:

// (returns the next line)
int executeCurrentLine() {
    String line = lines.get(currentIndex);

    if (line.startsWith("GOTO")) {
        return Integer.parseInt(line.substring(4).trim());
    } else if (line.startsWith("PRINT")) {
        String name = line.substring(5).trim();
        System.out.println(vars.get(name));
    } else {
        // and so on
    }
    return currentIndex + 1;
}

Then you do something like this:

while (currentIndex < lines.size()) {
    currentIndex = executeCurrentLine();
}

There are of course lots of ways you could make it more sophisticated but I hope that gives you some ideas of how to approach something like this starting out.

edit: One improvement over the above simple scheme would be to create an abstract class:

abstract class Command {
    // where Context is some object that lets
    // the command e.g. access variables
    abstract void execute(Context context);
}

// and for example
class GoToCommand extends Command {
    final int lineNumber;
    GoToCommand(String line) {
        lineNumber = Integer.parseInt(line.substring("GOTO".length()).trim());
    }
    @Override
    void execute(Context context) {
        context.setCurrentLine(lineNumber);
    }
}

Then instead of doing parsing and evaluation at the same time, you'd parse the List<String> of lines and create a List<Command> . This would let you split up the program logic in a meaningful way.

Java 8 streams for parsing instructions

Using code like this:

Files.lines(Paths.get("Test.txt"))
                .map(p -> p.toUpperCase())
                .collect(Collectors.toList());

You can take all the lines in the file, transform them (in this example I just made the strings uppercase, you would want to convert them into usable instructions, however you store them internally), and then store the resulting items into a list ready to be used.

Processing the items in the list

You would want an instruction pointer, and then depending on the instruction at that point you can follow to the next instruction, jump to another point, or terminate execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM