3

How would it be possible to create a 2D array of characters in Java? I've researching this as applicable to my goal of a map you can move a character around on, though have not found anything helpful. I have done this (with a little help) in C++ before, though don't know how to in Java.

For the C++ version, I started with a 1D array of strings:

    "#######.#.~~~####.##.......~~~..##.~~....H....######..#######",
    "#####..T.#~~~..##.H......~~~...#..T.~~.........######.###....",
    "######..~~~~#######...#..~~~.........~~~.##.###..#####.###...",
    "...###..~~~.######...##H.~~~.@........~~.#.####...##.H.###...",
    ".#####..~~.~~###C.....#..~~~.....#...~~~..###..#....##....#..",
    "######....~~~.~.##....#..~~~.....#....~~~.#######C...........",
    "#######.H..~.~~~~#....#..~~~.....###...~~~.##########........",
    "########.H...~~~~~.....~~~......H..##....~~~.H######...T...##",

(You are the @ Symbol) And then was able to break each string up into separate characters with 2 nested for loops that broke it into what was basically a 2D array that you could move your character around in.

Is this a good way of doing it, if so how? (I've spent 10 hours now attempting to get a basic version to work). Is there a better way of doing this? I would like to create a very complex game later on with a map like this, but need help coming up with how.

1
  • You would need nested for loops going through each line of that string and then putting every .charAt(index) into a position in the array. Remember 2D arrays are array[rows][cols] = string.charAt(x) Commented Oct 13, 2015 at 2:02

3 Answers 3

1

Well do you need 2D array for your String? Why not store a String like "ABCDEFGHI" and access it as if it was 3x3 2D array?

Map x,y "coordinates" to index.

public class Char2DDemo
{
    public static int ROWS = 3;
    public static int COLS = 3;

    public static class Char2D
    {
        private StringBuilder sb = null;
        private int ROWS;
        private int COLS;

        public Char2D(String str, int rows, int cols)
        {
            this.sb = new StringBuilder(str);
            this.ROWS = rows;
            this.COLS = cols;
        }

        public StringBuilder getSb()
        {
            return sb;
        }

        public int getRowCount()
        {
            return ROWS;
        }

        public int getColCount()
        {
            return COLS;
        }

        public int xy2idx(int x, int y)
        {
            int idx = y * getRowCount() + x;
            return idx;
        }

        public int idx2x(int idx)
        {
            int x = idx % getRowCount();
            return x;
        }

        public int idx2y(int idx)
        {
            int y = (idx - idx2x(idx)) / getRowCount();
            return y;
        }

        public Character getCh(int x, int y)
        {
            return getSb().charAt(xy2idx(x, y));
        }

        public void setCh(Character ch, int x, int y)
        {
            getSb().setCharAt(xy2idx(x, y), ch);
        }
    }

    public static void main(String[] args) throws java.lang.Exception
    {
        String test = "ABC"
                    + "DEF"
                    + "GHI";

        Char2D c2d = new Char2D(test, 3, 3);

        System.out.println("Before " + c2d.getSb());
        System.out.println("at [2][2] " + c2d.getCh(2, 2));
        c2d.setCh('J', 0, 0);
        c2d.setCh('K', 2, 2);
        c2d.setCh('M', 1, 1);        
        System.out.println("After " + c2d.getSb());
        System.out.println("at [1][0] " + c2d.getCh(1, 0));
    }
}

Output:

Before ABCDEFGHI
at [2][2] I
After JBCDMFGHK
at [1][0] B
Sign up to request clarification or add additional context in comments.

3 Comments

So I've been reading this approach, and just want to clarify how it handles the array. So it is technically just a 2D array? How then does it seem to take output from a 2D array? Thank you for the help
You can think of String as an array of Characters. It's just some specific array. :) Each index is from range [0..n] where n is the number of characters in that String. Specific index 0<=i<n let's us access a character from that String with a method .characterAt(i). Besides any 2D array technically is 1D array.
Oh ok, that makes sense, now I can see how they are accessed, thank you for the help!
1

You can create a 2D array in Java by doing

char[][] arr = new char[number of rows][number of columns];

For example,

char[][] arr = new char[2][3];

would create an array that is 2 rows tall and 3 columns wide. Therefore, you could have your character move up and down the grid by changing the row, and have it move left and right by changing the column.

Comments

1

The answer for this question is exactly what you want but with integers.

char[][] multi = new char[number of lines][number of columns];

But I really recommend you use some solution using Objects instead. Since you are using Java.

I don't know your project but I imagine that is a tile based 2D game. You could have a Tile class that have the position information and all properties of a tile.

Another approaches can be used thinking in scalability and performance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.