0

I created a 2D array(called names) to store string values. Initially, I assign all the elements in the array to blanks. I do this by having a variable that stores the maximum rows and iterate through the array filling its elements with blanks.

public class Untitled
{
    public static void main(String[] args) 
    {
        int maxRows = 10 ;

        String names[][] = new String[maxRows][2] ;

        int y = 0 ;
        while(y <= maxRows)
        {
            int x = 0 ;
            while (index < 2)
            {
                names[y][x] = " " ;
                index++ ;               
            }

            counter++ ;
        }       
    }
}

However, once the code is compiled and run, I get an error saying "Exception in thread "main" java.lang.ArrayOutOfBoundsException : 10"

  • 3
    Replace `<= maxRows` with `< maxRows`. The highest index is 9, since arrays are zero-indexed. – MC Emperor Jun 09 '20 at 14:46
  • 1
    You're never updating the ```x``` or ```y``` value that actually traverse the matrix. – kshitij86 Jun 09 '20 at 14:47
  • If you could explain why did you have `while(index < 2)` and not `while( index <= 2)` you have answered yourself. – SomeDude Jun 09 '20 at 14:47
  • 2
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – OH GOD SPIDERS Jun 09 '20 at 14:48
  • 1
    The code as posted here does not cause the error you claim: https://repl.it/@codeguru/BoilingCurlyInterfacestandard#Main.java. There is a mismatch in variable usage. You have `int y = 0` and `y <= maxRows`, but later `counter++` when it should be `y++`. – Code-Apprentice Jun 09 '20 at 14:48

2 Answers2

2

Change y <= maxRows to y < maxRows. The highest index is 9 in an array of 10 elements. You will also need to change counter++ to y++ in order to increment y.

Also, x never changes, so you are only filling the first column with blanks. You should change index < 2 to x < 2 and index++ to x++.

Finally, I suggest you learn about for loops.

Code-Apprentice
  • 69,701
  • 17
  • 115
  • 226
1

You can use Arrays#fill

public class Untitled {
   public static void main(String[] args) {
      int maxRows = 10 ;
      String names[][] = new String[maxRows][2] ;
      for(String[] row : names){
          Arrays.fill(row, " ");
      }
   }
}
Eritrean
  • 9,903
  • 1
  • 15
  • 20