如何在Java中从文本文件中读取数据网格?
当我说网格时,我指的是多维数组。我想要这个,因为我正在制作一个2D游戏,我希望能够从数据文本文件加载关卡。比如说,我有一个2D数组如何在Java中从文本文件中读取数据网格?,java,arrays,grid,nosuchelementexception,Java,Arrays,Grid,Nosuchelementexception,当我说网格时,我指的是多维数组。我想要这个,因为我正在制作一个2D游戏,我希望能够从数据文本文件加载关卡。比如说,我有一个2D数组level[3][3]。一张简单的3x3地图。我还有一个文本文件,上面写着: 1 2 3 4 5 6 7 8 9 在C++中,我可以简单地做: for (x=0; i<map_width; x++) { for (y=0; y<map_height; y++) { fscanf(nameoffile, "%d", map
level[3][3
]。一张简单的3x3地图。我还有一个文本文件,上面写着:
1 2 3
4 5 6
7 8 9
在C++中,我可以简单地做:
for (x=0; i<map_width; x++)
{
for (y=0; y<map_height; y++)
{
fscanf(nameoffile, "%d", map[x][y]);
}
}
for(x=0;i在Java中,它的工作原理类似-为您的文件创建一个Java.util.Scanner
对象,并使用它的nextInt
方法而不是fscanf。当涉及到文本文件的实际格式时,您的问题是毫无帮助的。例如
123
456
789
与
1 2 3
4 5 6
7 8 9
而且,您还没有提到它们是否总是int,或者
1 2 3
4 5 6
a b c
等等。如果您能准确描述这些文本文件中的内容,我们可以为您提供更多帮助。我所能做的就是向您展示如何使用扫描仪输入内容:
for循环在Java中看起来类似,但必须初始化Scanner对象
Scanner input = new Scanner(myFile); //whatever file is being read
for (x=0; i<map_width; x++)
{
for (y=0; y<map_height; y++)
{
int nextTile = input.nextInt(); //reads the next int
// or
char nextTile = input.nextChar(); //reads the next char
}
}
Scanner input=new Scanner(myFile);//正在读取的任何文件
对于(x=0;i,如果您不知道网格的尺寸
static int[][] readFile(String filename) {
try {
File textfile = new File (GridSearchTest.class.classLoader.getResource(filename).toURI());
Scanner fileScanner = new Scanner(textfile);
int size = Integer.parseInt(fileScanner.next());
String line = fileScanner.nextLine();
int[][] grid = new int [size][size];
int i = 0; int j = 0;
while (fileScanner.hasNextLine()) {
line = fileScanner.nextLine();
System.out.println (line);
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNext()) {
grid[i][j] = Integer.parseInt(lineScanner.next());
i++;
}
lineScanner.close();
i=0;
j++;
}
fileScanner.close();
return grid;
} catch (IOException e) {
System.out.println("Error reading file: "+ e.getMessage());
System.exit(0);
};
}
它们只是整数,每个数字对应一个不同的平铺。它们的格式完全没有空格,行与行之间没有额外的空行。像这样-123 456 789空格表示文件中的下一行。只要它们间隔开,并且文件格式正确(每行的整数数与宽度等相同)input.nextInt()我将按顺序阅读它们。就是这样!非常感谢!我只需要在文件中的数字之间添加空格。我做了一个测试,它工作得非常好!@Keelx,欢迎使用so。一个习惯性的感谢礼物是向上投票和/或接受答案。嘿,除了现在它使我的小程序得到一个灰色屏幕,没有任何错误…我知道它没有任何问题做文件加载,因为它加载了一个图像刚刚好。请接受我们的SO专家的答案。请解释代码,以便未来的读者理解它并从中学习。粘贴代码不会帮助任何人。
static int[][] readFile(String filename) {
try {
File textfile = new File (GridSearchTest.class.classLoader.getResource(filename).toURI());
Scanner fileScanner = new Scanner(textfile);
int size = Integer.parseInt(fileScanner.next());
String line = fileScanner.nextLine();
int[][] grid = new int [size][size];
int i = 0; int j = 0;
while (fileScanner.hasNextLine()) {
line = fileScanner.nextLine();
System.out.println (line);
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNext()) {
grid[i][j] = Integer.parseInt(lineScanner.next());
i++;
}
lineScanner.close();
i=0;
j++;
}
fileScanner.close();
return grid;
} catch (IOException e) {
System.out.println("Error reading file: "+ e.getMessage());
System.exit(0);
};
}