用Java逐字符读取文本文件到2D数组中 [英] Reading a text file character by character into a 2D array in Java
问题描述
作为我的面向对象课程的一部分,我们将设计一个战舰游戏,该游戏使用TUI最终实现GUI。
根据设计,我们将从一个类似于b的文本文件中读取AI的飞船位置
As part of my Object Oriented class, we are to design a Battleship game which uses a TUI to eventually implement a GUI. According to the design, we are to read the AI's ship locations from a text file that will look similar to the one b
ABCDEFGHIJ
1
2 BBBB
3
4 C
5D C
6D
7AAAAA
8 SSS
9
0
其中字母代表不同的船。我当前的游戏实现使用二维字符数组,因此我希望能够读取文本文件并创建相应的2D数组。我看到了一些内置函数,可让您读取下一个String或下一个Integer,但我只想逐个字符地读取它。有没有办法做到这一点?
提前谢谢!
Where the letters represent different ships. My current implementation of the game uses a 2 dimensional array of characters, so I would like to be able to read the text file and create the corresponding 2D array. I've seen a few built in functions that allow you to read the next String or the next Integer, but I just want to read it character by character. Is there a way to do this? Thanks in advance!
推荐答案
最简单的方法是先逐行读取文件,然后再读取行逐个字符。通过使用内置实用程序,可以避免处理新行的复杂性,因为它们会因OS / Editor而异。
The simplest way to do this, in my opinion, is to first read the file line-by-line then read those lines character-by-character. By using a built-in utility, you can avoid the complexities of handling new lines because they vary by OS/Editor.
BufferedReader fileInput = new BufferedReader(new FileReader("example.txt"));
String s;
while ((s = fileInput.readLine()) != null) {
for (char c : s.toCharArray()) {
//Read into array
}
}
fileInput.close();
这篇关于用Java逐字符读取文本文件到2D数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!