Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Problem with Multi-Dimensional Arrays

  1. #1
    Junior Member
    Join Date
    Aug 2013
    Posts
    8
    My Mood
    Nerdy
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Question Problem with Multi-Dimensional Arrays

    I can get the Tic Tac Toe game board to print, but not the other game boards.

    I get ArrayIndexOutOfBoundsException: 6
    which is the second array's row.

    If I edit the Board(), I can get the other boards to print but the columns end up being the same number as the rows.

    My question is where do the columns mirror the rows? And/Or What other method do I need to run to get the 3 boards to print?

    package boardgametester;
    import games.board.*;    
     
    /**
     *
     * @author Gorgo
     */
     
    public class BoardGameTester {
     
     
     
     
        public static void main(String[] args) {
     
             // 3x3 board for Tic Tac Toe
           Board tttgameboard = new Board (3,3);
     
            // 6x7 board for Connect Four
           Board cfgameboard = new Board (6,7);
     
           // 5x8 board for Mastermind; blue mark
           Board mmgameboard = new Board (5,8);    
     
     
            System.out.println (" Tic Tac Toe game board ");
            tttgameboard.setCell(Mark.NOUGHT,1,1);
            System.out.println(tttgameboard.toString());
     
            System.out.println(" Connect Four game board ");
            cfgameboard.setCell(Mark.YELLOW,0,0);
            System.out.println(cfgameboard.toString());
     
            System.out.println (" Mastermind game board ");
            mmgameboard.setCell(Mark.BLUE,0,0);
            System.out.println(mmgameboard.toString());
     
     
     
     
        }
    }

    Board Class

    package games.board;
     
    public class Board {
              private Cell[][] cells;
     
            public Board(int rows, int columns) {
                cells = new Cell[rows][columns];
                for (int r = 0; r < cells[0].length; r++) {              //I can get the other game boards to print if I take out: [0]
                    for (int c = 0; c < cells[1].length; c++) {        // and [1]
                       cells [r][c] = new Cell (r,c);
     
                    }
                }
             }
     
     
             public void setCell (Mark mark, int row, int column) throws
                    IllegalArgumentException {
                        if (cells[row][column].getContent() == Mark.EMPTY)
                            cells[row][column].setContent(mark);
                        else throw new IllegalArgumentException ("Player already there!");
            }
            public Cell getCell(int row, int column) {
     
                return cells[row][column];
            }
     
     
            public String toString() {
                StringBuilder str = new StringBuilder();
     
                for (int r = 0; r < cells.length; r++) {
                    str.append("|");
                    for (int c = 0; c < cells.length; c++) {
                        switch (cells[r][c].getContent()) {
                            case NOUGHT:
                                str.append("O");
                                break;
                            case CROSS:
                                str.append("X");
                                break;
                            case YELLOW:
                                str.append("Y");
                                break;
                            case RED:
                                str.append("R");
                                break;
                            case BLUE:
                                str.append("B");
                                break;
                            case GREEN:
                                str.append("G");
                                break;
                            case MAGENTA:
                                str.append("M");
                                break;
                            case ORANGE:
                                str.append("N");
                                break;
                            default:            //Empty
                                str.append(" ");
                        }
                        str.append("|");
                    }
                    str.append("\n");
                }
                return str.toString();
            }
        }

    And the Cell class

    public class Cell {
        private Mark content;
        private int row, column;
     
        public Cell(int row, int column) {
            this.row = row;
            this.column = column;
        content = Mark.EMPTY;
        }
     
        public Mark getContent() { return content;}
     
        public void setContent (Mark content) { this.content = content; }
     
        public int getRow() { return row; }
     
        public int getColumn() { return column; }
    }


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,787
    My Mood
    Mellow
    Thanks
    236
    Thanked 717 Times in 703 Posts

    Default Re: Problem with Multi-Dimensional Arrays

    Try:
          for (int r = 0; r < cells.length; r++) {              //I can get the other game boards to print if I take out: [0]
              for (int c = 0; c < cells[r].length; c++) {        // and [1]
    If it works and you'd like me to explain it, let me know.

  3. #3
    Junior Member
    Join Date
    Aug 2013
    Posts
    8
    My Mood
    Nerdy
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Problem with Multi-Dimensional Arrays

    That was the first thing I tried and I get rows = columns. So the 6x7 Connect Four board comes out 6x6.

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,787
    My Mood
    Mellow
    Thanks
    236
    Thanked 717 Times in 703 Posts

    Default Re: Problem with Multi-Dimensional Arrays

    It was a guess, because the code you had there was suspect, but I can't do better because you haven't given us code that we can run (missing something called 'Mark' and maybe others), and you haven't explained your problem very well.
    That was the first thing I tried . . .
    That's not what your post said. You said you took out the [0] and the [1]. It's important that you take out the [0] and replace the [1] with an [r].

    As the error message says, if you're creating a board of 6 rows by 7 columns, the max index for rows should be 5 and for columns 6. The code I suggested should work for all board dimensions.

    If you want help with an error message, copy and paste the error message into your post EXACTLY as it appears at your end, and point to the line numbers it refers to in code you've posted. Don't interpret or excerpt it.

  5. #5
    Junior Member
    Join Date
    Aug 2013
    Posts
    8
    My Mood
    Nerdy
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Problem with Multi-Dimensional Arrays

    Ok, you are right, I need to be more specific:

    Here is all of the code that you need to run the program:

    1. the BoardGameTester class

    import games.board.*;    
     
    /**
     *
     * @author Gorgo
     */
     
    public class BoardGameTester {
     
        public static void main(String[] args) {
     
             // 3x3 board for Tic Tac Toe
           Board tttgameboard = new Board (3,3);
     
            // 6x7 board for Connect Four
           Board cfgameboard = new Board (6,7);      // LINE 25: ERROR
     
           // 5x8 board for Mastermind; blue mark
           Board mmgameboard = new Board (5,8);    
     
     
            System.out.println (" Tic Tac Toe game board ");
            tttgameboard.setCell(Mark.NOUGHT,1,1);
            System.out.println(tttgameboard.toString());
     
            System.out.println(" Connect Four game board ");
            cfgameboard.setCell(Mark.YELLOW,0,0);
            System.out.println(cfgameboard.toString());
     
            System.out.println (" Mastermind game board ");
            mmgameboard.setCell(Mark.BLUE,0,0);
            System.out.println(mmgameboard.toString());
     
     
     
     
        }
    }

    2. the Board class
    package games.board;
     
    public class Board {
              private Cell[][] cells;
     
            public Board(int rows, int columns) {
                cells = new Cell[rows][columns];
                for (int r = 0; r < cells[0].length; r++) { 
                    for (int c = 0; c < cells[1].length; c++) {  
                       cells [r][c] = new Cell (r,c);                               //LINE 10: ERROR
     
                    }
                }
             }
     
     
             public void setCell (Mark mark, int row, int column) throws
                    IllegalArgumentException {
                        if (cells[row][column].getContent() == Mark.EMPTY)
                            cells[row][column].setContent(mark);
                        else throw new IllegalArgumentException ("Player already there!");
            }
            public Cell getCell(int row, int column) {
     
                return cells[row][column];
            }
     
     
            public String toString() {
                StringBuilder str = new StringBuilder();
     
                for (int r = 0; r < cells.length; r++) {
                    str.append("|");
                    for (int c = 0; c < cells.length; c++) {
                        switch (cells[r][c].getContent()) {
                            case NOUGHT:
                                str.append("O");
                                break;
                            case CROSS:
                                str.append("X");
                                break;
                            case YELLOW:
                                str.append("Y");
                                break;
                            case RED:
                                str.append("R");
                                break;
                            case BLUE:
                                str.append("B");
                                break;
                            case GREEN:
                                str.append("G");
                                break;
                            case MAGENTA:
                                str.append("M");
                                break;
                            case ORANGE:
                                str.append("N");
                                break;
                            default:            //Empty
                                str.append(" ");
                        }
                        str.append("|");
                    }
                    str.append("\n");
                }
                return str.toString();
            }
        }

    3. the Cell class
     
    package games.board;
     
    public class Cell {
        private Mark content;
        private int row, column;
     
        public Cell(int row, int column) {
            this.row = row;
            this.column = column;
        content = Mark.EMPTY;
        }
     
        public Mark getContent() { return content;}
     
        public void setContent (Mark content) { this.content = content; }
     
        public int getRow() { return row; }
     
        public int getColumn() { return column; }
    }

    4. the Mark class

    package games.board;
     
    //Result when game is completed
    public enum Mark {EMPTY, NOUGHT, CROSS, YELLOW, RED, BLUE, GREEN, MAGENTA, ORANGE}

    And here is the error code:
    run:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
    at games.board.Board.<init>(Board.java:10)
    at boardgametester.BoardGameTester.main(BoardGameTest er.java:25)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)

    So, I have tried fixing the Board() to not get an OutOfBounds error:

    public class Board {
              private Cell[][] cells;
     
            public Board(int rows, int columns) {
                cells = new Cell[rows][columns];
                for (int r = 0; r < cells[0].length; r++) {       // taking out [0]; replacing [0] w/ [c]
                    for (int c = 0; c < cells[1].length; c++) {  //taking out [1]; replacing [1] w/ [r]
                       cells [r][c] = new Cell (r,c);
     
                    }
                }
             }

    I have also tried this to see where the error was:
    System.out.println("Rows" + rows);
    System.out.println("Columns"+ columns);

    In various places (before Board(), after Board(), before and after each line in Board()) and it prints out the correct numbers of array size (3x3, 6x7, 5x8), but the end game boards do not print with these sizes.

    When I run these corrections, I don't get any errors, but my arrays are 3x3 (Tic Tac Toe), 6x6 (Connect Four) instead of 6x7 and 5x5 (Mastermind) instead of 5x8.

    My question is: How do I get my arrays to print out the correct sizes? = 3x3, 6x7, and 5x8

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,787
    My Mood
    Mellow
    Thanks
    236
    Thanked 717 Times in 703 Posts

    Default Re: Problem with Multi-Dimensional Arrays

    Did you try the change I suggested? I've tried it, and it works fine IF you correct both the Board() constructor AND the toString() method.

  7. The Following User Says Thank You to GregBrannon For This Useful Post:

    NickieBoren (August 30th, 2013)

  8. #7
    Junior Member
    Join Date
    Aug 2013
    Posts
    8
    My Mood
    Nerdy
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Problem with Multi-Dimensional Arrays

    Thank you! I wasn't changing it in the toString()!!

Similar Threads

  1. Convert ArrayList to multi-dimensional array
    By dougie1809 in forum Loops & Control Statements
    Replies: 4
    Last Post: April 5th, 2013, 12:01 PM
  2. How to begin with multi-dimensional arrays
    By Lorelai in forum Java Theory & Questions
    Replies: 1
    Last Post: April 6th, 2012, 06:56 PM
  3. Searching and displaying results in a multi-dimensional array.
    By wfalcon2012 in forum Collections and Generics
    Replies: 2
    Last Post: February 18th, 2012, 07:06 PM
  4. How can I create a jigsaw puzzle with Array multi-dimensional?
    By ivan8 in forum What's Wrong With My Code?
    Replies: 15
    Last Post: December 4th, 2011, 07:13 PM
  5. Multi Dimensional Array help NEEDED URGENT
    By bonjovi4u in forum Loops & Control Statements
    Replies: 5
    Last Post: February 12th, 2010, 11:44 PM