0

I am trying to create an mxm grid using a 2D array where the user can input data. The first column must be a column of . whereas all the other columns must be a *. The user is allowed to enter any letter they want into the String array, However, directly after the user enters the data a . must precede the letter. So the array should look like this:

.g.*****
.g.*****

I have managed to get the . after element except for when I try to input a value into the with column so index[7]. When I enter a value in the eighth column I get the ArrayIndexOutOfBoundsException. The thought process was that if the column element j is equal to the last index in the array, then it should just be a value, and no . should precede it and if the column element is less than the second last index in the array then a . should precede the element, however, this does not happen and I get the ArrayIndexOutOfBounds error.

import java.util.Arrays;

public class trial1 {
 
// Function prints the game board out with its original values (Null)
    public static void impasseBoard(String[][] gameBoard, int m) {
        for(int i = 0; i<gameBoard.length; i++) {
            for(int j = 0; j<gameBoard[i].length; j++) {
                StdOut.print(gameBoard[i][j]);
            }
            StdOut.println();
        }
    }

 public static void main(String[] args) {
     int m = 8;
     
    // Creates the 2D Array
        String[][] gameBoard = new String[m][m];
        
        // Changes the elements within the array to open and closed elements
        for(int i = 0; i<gameBoard.length; i++) {
            Arrays.fill(gameBoard[i], "*");
            gameBoard[i][0] = ".";
 }
        
        StdOut.println("Row: ");
        int pRow = StdIn.readInt();
        StdOut.println("Column: ");
        int pCol = StdIn.readInt();
        StdOut.println("Colour: ");
        String colour = StdIn.readString();
        gameBoard[pRow][pCol] = colour; 
        for(int i=0; i<gameBoard.length; i++) {
            for(int j=0; j<gameBoard.length; j++) {
                if(j==m-1) {
                    gameBoard[pRow][pCol] = colour; 
                }else if(j<m-2) { 
                    gameBoard[pRow][pCol+1] = "."; 

                }
                
            }
        }


        impasseBoard(gameBoard, m);
     }
   }

When I change the conditional statement slightly to:

                if(gameBoard[pRow][m-1] == colour) {
                    gameBoard[pRow][pCol] = colour; 
                }else if(j<m-2) { 
                    gameBoard[pRow][pCol+1] = "."; 

                }

The code now does what it is supposed to. I want to know what the difference between the two is.

  • Don't use `==` to compare Strings for equality; use `str1.equals(str2)`. See [How do I compare strings in Java?](https://stackoverflow.com/questions/513832) – Bohemian Apr 17 '22 at 01:58

0 Answers0