Search code examples
javaloopsindexoutofboundsexceptionchess

How can I print the given pattern with just a loop and an inner loop? Instead of using 4 loops


This is the code snippet, which should mark the Field of a Bishop (chess figure)
Sadly and obviously I am getting an array out of bounds exceptions - can someone solve the issue please?

int i = 1, j = 1;

 while (i <= 8) {
      board.markField(9-i, i);

      i++;

      while (j <= 8) {

          board.markField(j, i); // here is the error
          j++;      // j =2
          break;
      }
  }

Desired Output

o o o o o o o x
x o o o o o x o
o x o o o x o o
o o x o x o o o
o o o x o o o o
o o x o x o o o
o x o o o x o o
x o o o o o x o

It is not necessary, to help me with printing out the x or the o, I have a working function, that does this very good

 public void markField(int x, int y){

     board[x-1][y-1] = true;
 }


Solution

  • Two for-loops are enough to get it done, however, you will have to have some extra variables to get it done. Code:

    int start = 0, end = 7;
    boolean flag = false;
    for(int i= 0; i<8; i++)
    {
        if(i > 0)
            flag = true;
        for(int j= 0; j<8; j++)
        {
            if(flag && j==start)
            {
                //System.out.printf("x ");
                board.markField(i,j);
                start++;
                if(start == end+1)
                    end--;
                flag = false;
                continue;
            }
    
            if(j==end)
            {
                //System.out.printf("x ");
                board.markField(i,j);
                end--;
                continue;
            }
            //System.out.printf("o ");
            board.markField(i,j);
        }
        //System.out.println();
    }
    

    As we are calling markField() with correct array indices, so, change your markField() like this:

    public void markField(int x, int y){
    
     board[x][y] = true;
    }