Java: Getting coordinates of a character, read out of a file

640 Views Asked by At

Good evening,

for hours I've been searching for a solution for this problem without success so I figured I'd ask a question here! I have a question regarding reading characters / lines out of a textfile. I have been able to implement a function, which reads lines out of a file. I am using Greenfoot (Java) to create a game which uses 32x32 blocks. I'd like to generate a world out of that textfile by getting the x- / y-coordinate of each "block" / "character" and placing it in the world. Would it be easier to use an array? My current code looks like this but I cannot figure out, how to get the coordinates. Could it work by using the hashcode it returns?

    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 {

    }
}

My file looks somewhat like this:

0000000000
0000000000
AAAAAA00AA
BBBBBB00BB

I see that I have assigned the value "0" to both x and y so of course it can't work like this but how can I get that position? Right now the function is able to read the lines, generate the blocks at (0, 0) and showing the blocks in the console with a hashcode.

P.S Sorry if I have used the wrong term for some things, I am relatively new to programming!

Thank you, Julian

1

There are 1 best solutions below

1
On

Just the very basic, without changing question code too much, not complete

  1. determining the line number y:

    int y = 0;
    while ((s = ...) != null) {
        // do something with s
        y += 1;  // or y++
    }
    
  2. similar for character position x inside the line and using charAt to retrieve the character:

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

Notes: x is declared inside the outer (first) loop since it is not needed elsewhere; x is set to zero before the inner loop since it is the start of a new line; a for loop could be used instead of while - mostly better when using counters (like x)