Java:获取字符的坐标,从文件中读取

时间:2017-05-11 19:42:03

标签: java greenfoot

晚上好,

几个小时我一直在寻找这个问题的解决方案但没有成功,所以我想我在这里问一个问题! 我有一个关于从文本文件中读取字符/行的问题。我已经能够实现一个函数,它从文件中读取行。 我正在使用Greenfoot(Java)创建一个使用32x32块的游戏。我想通过获取每个“块”/“字符”的x- / y坐标并将其放在世界中来生成该文本文件中的世界。使用数组会更容易吗?我当前的代码看起来像这样,但我无法弄清楚,如何获得坐标。它可以使用它返回的哈希码吗?

    public void readFile(String filename) throws IOException
{      
    String s;
    int x = 0;
    int y = 0;

    // Create BufferedReader and FileReader
    BufferedReader r = new BufferedReader(new FileReader(filename));

    // Try-catch block as exception handler 
    try {
        while((s = r.readLine()) != null) {

            // Create the blocks
            GrassBlock A = new GrassBlock();

            // Place them in the world
            addObject(A, x, y);

            // Test to see, if the blocks get recognised
            System.out.println(A);

            DirtBlock B = new DirtBlock();
            System.out.println(B);
            addObject(B, x, y);
        }            
    } catch (IOException e) {
        System.out.println("Fehler beim Öffnen der Datei");
    } finally {

    }
}

我的文件看起来有点像这样:

0000000000
0000000000
AAAAAA00AA
BBBBBB00BB

我看到我已经为x和y分配了值“0”,所以当然它不能像这样工作但是我怎么能得到那个位置?现在,该函数能够读取行,在(0,0)生成块,并在控制台中显示带有哈希码的块。

P.S很抱歉,如果我对某些事情使用了错误的术语,我对编程相对较新!

谢谢你, 儒略

1 个答案:

答案 0 :(得分:0)

只是非常基本的,没有变化的问题代码太多,不完整

  1. 确定行号y:

    int y = 0;
    while ((s = ...) != null) {
        // do something with s
        y += 1;  // or y++
    }
    
  2. 类似于行内的字符位置x并使用charAt来检索字符:

    while ((s = ...) != null)  {
        int x = 0;
        while (x < s.length()) {
            char ch = s.charAt(x);
            // do something with ch, x, y - test for 0, A or B and add block
            x += 1;  // or x++
        }
        y += 1;  // or y++
    }
    
  3. 注意:x在外部(第一个)循环内声明,因为在其他地方不需要它;在内循环之前将x设置为零,因为它是新行的开始;可以使用for循环代替while - 使用计数器时更好(例如x