如何使用BufferedReader移动.txt文件中的行?(How to move up lines in a .txt file with BufferedReader?)

编程入门 行业动态 更新时间:2024-10-27 16:25:17
如何使用BufferedReader移动.txt文件中的行?(How to move up lines in a .txt file with BufferedReader?)

为我注册的CS课程制作“汇编程序”。它具有ADD,SET,INC(增量)和JIG等功能。 现在,我们输入一个带有以下布局的.txt文件(例如):

请注意:A和B只是整数,它存储整个程序的值,并在文本到达文本文件末尾时打印出来。

INC A (increments A by 1) SET B 5 (set's B's value to 5) INC B ADD A 3 (add's 3 to A's current value) JIG B -4 (move's backward 4 lines, so back to INC A)

所以我感到困惑的是如何将我的BufferedReader移回4行? BufferedReader中是否有一个方法可以将它移动到某个索引/位置? 否则,我怎么能做到这一点?

Making an "assembler" program for a CS course I am enrolled in. It has functions like ADD, SET, INC (increment), and JIG. Now, we are inputing a .txt file with the following layout (as example):

Keep note: A and B are just integer's that store the value throughout the program, and print out the value once it reaches the end of the text file.

INC A (increments A by 1) SET B 5 (set's B's value to 5) INC B ADD A 3 (add's 3 to A's current value) JIG B -4 (move's backward 4 lines, so back to INC A)

So what I am confused how to do is move my BufferedReader back 4 lines? Is there a method in BufferedReader that lets you move it to a certain index/position? Otherwise, how else can I accomplish this?

最满意答案

最简单的方法是将行存储在数组或List中。

List<String> lines = Files.readAllLines(Paths.get("myfile.txt"));

这将允许您随机前进到任何行。

要获得任何行,您可以使用lines.get(n)例如,您可以这样做

int pointer = 0; for(boolean running = true; running && pointer < lines.size(); ) { String line = lines.get(pointer); String[] parts = line.split(" +"); switch(part[0]) { case "JMP": pointer += Integer.parseInt(parts[1]); // jump back or forth. continue; case "HALT": running = false; break; // other instructions } pointer++; }

The simplest thing to do is store the lines in an array or List.

List<String> lines = Files.readAllLines(Paths.get("myfile.txt"));

This will allow you to progress to any line at random.

To get any line you can use lines.get(n) For example you can do

int pointer = 0; for(boolean running = true; running && pointer < lines.size(); ) { String line = lines.get(pointer); String[] parts = line.split(" +"); switch(part[0]) { case "JMP": pointer += Integer.parseInt(parts[1]); // jump back or forth. continue; case "HALT": running = false; break; // other instructions } pointer++; }

更多推荐

本文发布于:2023-07-21 11:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1209774.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   文件   BufferedReader   file   txt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!