【发布时间】:2020-10-09 08:20:03
【问题描述】:
所以我有两种类型的文件,一种用于级别定义,另一种用于块结构定义。
我需要将它们都解析为包含行的字符串列表,然后遍历列表和每一行,拆分和解析并将它们映射到 java 对象中。
我不知道该怎么做,我已经阅读了有关 java io 阅读器的信息,但在这里我对在哪里以及如何使用它感到困惑。
了解单个关卡的关卡规范的内容:这将遍历字符串,拆分和解析它们,并将它们映射到java对象,从而产生一个LevelInformation对象。
P.S 我已经编写并构建了 LevelInformation 接口(如果我手动编写一个实现此接口的关卡,它就可以工作),它包含文本文件中的所有内容(关卡名称、速度、背景等) 所以基本上我只需要解析这些文本文件并将它们映射到这个界面中。
public interface LevelInformation {
int numberOfBalls();
// The initial velocity of each ball
// Note that initialBallVelocities().size() == numberOfBalls()
// velocities created by (a,s) format. a = angle, s = speed.
List<Velocity> initialBallVelocities();
int paddleSpeed();
int paddleWidth();
// the level name will be displayed at the top of the screen.
String levelName();
// Returns a sprite with the background of the level
Sprite getBackground();
// The Blocks that make up this level, each block contains
// its size, color and location.
List<Block> blocks();
// Number of blocks that should be removed
// before the level is considered to be "cleared".
// This number should be <= blocks.size();
int numberOfBlocksToRemove();
}
文件示例:
level_definition.txt
START_LEVEL
level_name:Square Moon
ball_velocities:45,500
background:image(background_images/night.jpg)
paddle_speed:650
paddle_width:160
block_definitions:definitions/moon_block_definitions.txt
blocks_start_x:25
blocks_start_y:80
row_height:100
num_blocks:4
START_BLOCKS
--ll--
--ll--
END_BLOCKS
END_LEVEL
block_definitions.txt
#block definitions
bdef symbol:l width:100 height:100 fill:color(RGB(154,157,84))
#spacers definitions
sdef symbol:- width:30
所以我需要创建一个列表并获取一个阅读器并以某种方式对其进行解析。 我很高兴获得一些提示、想法和帮助。 谢谢。
public class LevelSpecificationReader {
public List<LevelInformation> fromReader(java.io.Reader reader) {
// ...
}
}
我想我需要:
将文件分成几行并从中列出字符串。 这意味着每一行都将作为字符串进入列表。
获取每一行,也拆分成我不知道是什么,但是按顺序 获取信息并映射到所需的对象。例如:
level_name:某事 我必须在我的界面中将“某事”添加到“关卡名称”中。
这是我失败的尝试:
public List<LevelInformation> fromReader(java.io.Reader reader) throws IOException {
ArrayList<String> listOfLines = new ArrayList<>();
BufferedReader bufReader = new BufferedReader(new FileReader("file.txt"));
String line = bufReader.readLine();
while (line != null) {
listOfLines.add(line);
line = bufReader.readLine();
}
return listOfLines;
}
此代码会导致错误,因为我返回了一个字符串列表,但我需要一个 LevelInformation 列表。
【问题讨论】:
-
您需要展示您迄今为止尝试过的代码尝试,以便我们提供建议
-
@DeveshKumarSingh 我不知道如何编写它,因此我没有代码尝试。我的意思是我确实尝试过做某事,但它超级失败。我会附上它
-
感觉这是一道作业题,请看meta.stackoverflow.com/questions/334822/…
-
@DeveshKumarSingh 我确实尝试理解阅读器和解析的逻辑。我要求指导和提示。感谢您的帮助。
-
您在问题中写道:我需要 LevelInformation 列表您有
LevelInformation的代码吗?如果你这样做了,那么edit 你的问题并发布该代码,即LevelInformation的定义。是一堂课吗?是接口吗?一旦您发布了LevelInformation的定义,我或许可以向您展示如何从两个文本文件(即level_definition.txt 和)中创建LevelInformation对象的Listblock_definitions.txt
标签: java parsing filereader streamreader text-parsing