繁体   English   中英

如何使用BufferedReader将行放入ArrayList中,然后执行它们?

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

我正在尝试编写一个程序,该程序将执行并从文件生成简化的编程语言语句的输出。 文件中有几行将给出语句,例如变量=表达式,PRINT变量,GOTO'x行',IF变量IS值THEN ....等。最后一行表示END ,应该停止该程序。

我使用空格作为定界符,并且知道我将需要使用BufferedReader然后使用分词器来拆分这些行。 我苦苦挣扎的是如何将所有这些语句/变量拆分后存储起来? 并行ArrayLists是执行此操作的好方法吗? 如何分别读取每个变量和表达式并进行评估? 这是我到目前为止的内容:

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(" ");

    }


}

我是一个初学者,所以任何方向都很棒。

一种简单的方法是进行如下设置:

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

您可以使用Map<String, Double> vars; 将变量存储在其中。(请参阅Map教程 。)

然后有一个像这样的方法:

// (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;
}

然后,您可以执行以下操作:

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

当然,有很多方法可以使它更复杂,但是我希望可以为您提供一些有关如何开始这种方法的想法。

编辑:对上述简单方案的一种改进是创建一个抽象类:

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);
    }
}

然后,与同时进行解析和评估不同,您将解析行的List<String>并创建List<Command> 这将使您以有意义的方式拆分程序逻辑。

Java 8流用于解析指令

使用如下代码:

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

您可以将文件中的所有行转换为字符串(在本示例中,我只是将字符串设置为大写,您希望将它们转换为可用的指令,但是您将其存储在内部),然后将结果项存储到准备好的列表中要使用的。

处理列表中的项目

您可能需要一个指令指针,然后根据当时的指令,可以跟随下一条指令,跳转到另一点或终止执行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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