Magic Square Java program

Kevin Clement picture Kevin Clement · Sep 15, 2011 · Viewed 7.4k times · Source

//Kevin Clement //Week3A Magic Squares

Hey all, doing an introductory assignment to 2dimensional arrays. Below is the code I have done which is pretty much done.

My problem I get is I'm not entirely sure how to print out the array, as well as getting everything to run right with a test method. I get an error out of bounds at the line msq[order][order] = 1;

I apologize if my formatting of question is wrong, still not used to this site. Any help would be great. Thanks!

import java.util.*;

class Magic
{
  private int order;
  int msq[ ][ ];

  public Magic(int size)
  {
     if(size < 1 || size % 2 == 0)
     {
        System.out.print("Order out of range");
        order = 3;
     }
     msq = new int[order][order];
     Build();
     Display();
   }

  public void Build()
   {
     int row = 0;
     int col =0;
    msq[order][order] = 1;

     for(int k = 1; k <= order * order; k++)
     {
        msq[row][col] = k;

        if(row == 0 && col == order -1)
           row++;
        else if(row == 0)
        {
           row = order - 1;
           col++;
        }
        else if(msq[row - 1][col + 1] != 0)
           row++;
        else if(msq[row -1][col + 1] == 0)
        {
           row--;
           col++;
        }
        if(col == order - 1)
        {
           col = 0;
           row--;
        }

     }
  }
  public void Display()
  {

     for(int i = 0; i < order; i++)
     {
        for(int k = 0; k < order; k++)
        {
           System.out.println(msq[i][k] + " ");
        }
     }


  }
}

Answer

Mahesh picture Mahesh · Sep 15, 2011

I get an error out of bounds at the line msq[order][order] = 1;

msq = new int[order][order];
// ..
msq[order][order] = 1;

If array size is n, then you need to access the elements from 0 to n-1. There is no nth index. In your case there is no order, order index. It is only from 0 to order-1 and is the reason for array index out of bounds exception.