简体   繁体   中英

java.lang.ArrayIndexOutOfBoundsException: 0 - I cant figure out why the code is running out of bounds

i am getting the error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 This is a 2 part program. a service file, and a client file. (for a school project)

public String[][]gameBoard(int rows, int columns)
{

    for (rows = 0; rows<gameBoard[0].length; rows++)
    {

       for (columns = 0; columns<gameBoard[0].length; columns++)
       {
          gameBoard[rows][columns]=""; //initializes the values of the string array (gets rid of null)
          System.out.print(gameBoard[rows][columns]+"_ ");
       }
       System.out.println();
    }
    return gameBoard;
 }

Is the part that is getting the error, (making and printing a board, based on user input).

is how i am calling it in the client file. How or what is causing this to go out of bounds?

Thank you!

If you have initialized the 2D array correctly,

My Guess would be that your loops for row and column traversal is a little off...

In your code the first loop traverses the columns and so does the inner loop..

You need to traverse columns for each row.

I would try

for (rows = 0; rows<gameBoard.length; rows++)
{

   for (columns = 0; columns<gameBoard[rows].length; columns++)
   {
      gameBoard[rows][columns]=""; //initializes the values of the string array (gets rid of null)
      System.out.print(gameBoard[rows][columns]+"_ ");
   }
   System.out.println();
}
return gameBoard;

Your method signature indicated that you will return a thing of type String[][] , and that your method is called gameBoard . You're using this gameBoard as if it was an array, but there is no array called gameBoard at all.

I will not give you the source code just yet, as I do not want to do your homework, but I can tell you as much, that you need to create a new local String[][] inside the method body. It should be just as big as the row and columns you ask for as the method's parameters, and should be call something appropriate (like gameArr ).

Next up, your for-loops are slightly off. Use the parameters instead of the wrongly used method name - that's what they're here for, right? ;)

Lastly return your newly created local array.

I'm pretty sure at this point the line with gameBoard[0] is uninitialized.

Initialize gameBoard[] before trying to access [0].

http://www.dummies.com/how-to/content/java-use-arrays-with-two-dimensions-or-more.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM