0

当我说网格时,我的意思是多维数组。我想要这个,因为我正在制作一个 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[x][y]);
    }
}

这会将文本文件的所有内容相应地放入数组中。但是我不知道如何在java中做到这一点。是否有任何等价物可以将数据相应地放入数组中?我已经知道扫描仪类,但我不知道如何使用它。我已经搜索了谷歌,无济于事。它没有太多解释。请帮忙!具体来说,我想知道如何扫描文件并将它读取的任何 int 放入数组中的适当位置。

我当前的代码是这样的,但是,它抛出了 NoSuchElementException:

public void loadMap() {
    Scanner sc = null;
    try {
        sc = new Scanner(inputmap);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            map[x][y] = sc.nextInt();
        }
    }

其中 inputmap 是文件,map[][]是地图上每个图块的数据网格,并且宽度和高度在构造函数中预先指定。

4

3 回答 3

0

在 Java 中,它的工作方式类似 -java.util.Scanner为您的文件创建一个对象并使用它的nextInt方法而不是 fscanf。

于 2011-03-21T03:00:32.803 回答
0

当涉及到文本文件的实际格式化方式时,您的问题非常无用。例如,

123 
456
789

1 2 3
4 5 6
7 8 9

此外,您还没有提到它们是否总是整数,或者

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
    }
}

除此之外,我需要更多地了解这些输入文件中的实际内容。

编辑:

我直接从您的代码中复制了您的 for 循环,但您可能想要交换内部和外部 for 循环。宽度不应该是内部参数(从左到右读取)吗?

于 2011-03-21T03:29:03.857 回答
0

如果您不知道网格的尺寸

    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);
    };
}
于 2016-03-23T21:56:07.927 回答