简体   繁体   English

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

[英]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. 文件中有几行将给出语句,例如变量=表达式,PRINT变量,GOTO'x行',IF变量IS值THEN ....等。最后一行表示END ,应该停止该程序。

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. 我使用空格作为定界符,并且知道我将需要使用BufferedReader然后使用分词器来拆分这些行。 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? 并行ArrayLists是执行此操作的好方法吗? 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; 您可以使用Map<String, Double> vars; to store your variables in. (See Map tutorial .) 将变量存储在其中。(请参阅Map教程 。)

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> . 然后,与同时进行解析和评估不同,您将解析行的List<String>并创建List<Command> This would let you split up the program logic in a meaningful way. 这将使您以有意义的方式拆分程序逻辑。

Java 8 streams for parsing instructions Java 8流用于解析指令

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. 您可能需要一个指令指针,然后根据当时的指令,可以跟随下一条指令,跳转到另一点或终止执行。

暂无
暂无

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

相关问题 如何使用BufferedReader将String添加到ArrayList中? - How do I add String into ArrayList by use BufferedReader? 如何使用BufferedReader将txt文件中的行读取到数组中 - How do I use BufferedReader to read lines from a txt file into an array 当我使用 BufferedReader 从控制台读取字符并打印它们时,为什么会打印空行? - Why empty lines are being printed at the when I use BufferedReader to read characters from the console and print them? 关于如何测试接受字符串并将它们放入 ArrayList 的 BufferedReader 和 FileReader 的建议 - Suggestions on how to test a BufferedReader and FileReader that takes in strings and puts them into an ArrayList 如何将BufferedReader的内容放入String? - How do you put the content of a BufferedReader into a String? 在Java中,如何以一定的顺序执行代码行并在它们之间有延迟? - In Java, how do I execute lines of code in a certain order with a delay in between them? 如何将均值放入arrayList,如何将输入文件中的分数放入自己的arrayList中? - How do I put the mean into an arrayList, and how do I put the scores in the input file into their own arrayList? 如何分割多行并将其添加到arraylist - how to split multiple lines and add them to an arraylist 如何使用输入将一个字符串中的5个字符准确地放置并隔开 - How do I use an input to out put exactly 5 characters in a string and space them out 如何遍历arrayList将它们存储为不同的对象? - How do I loop through an arrayList to store them as different objects?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM