Question

I did an N queens java project that required me to print out a multidimensional array showing where I can place the queens. My array is of Ints. It prints out 1s and 0s in respectable positions. I was wondering if there was a way that I could print out a Q for queens in the place of a 1 and a space in the place of a 0, without changing my array to type String. I went back and changed my array to String type and I got nulls in the place of some 0's.

I tried converting the int to is ASCII character (81 would be a Q).

I also tried copying the Int array into a String array, but java doesnt allow that. Any Ideas?

    public void print(){

for(int i = 0; i < a.length; i++)
{

    for(int j = 0; j < a[i].length; j++)
    {
        if (a[i][j]==1){

            a[i][j]=((char)81);

        }
        System.out.print(a[i][j]);
        if(j < a[i].length - 1) System.out.print(" ");
    }
    System.out.println();
}

}

Solution :
0 0 0 0 0 81 0 0
81 0 0 0 0 0 0 0
0 0 0 0 0 0 81 0
0 0 0 81 0 0 0 0
0 81 0 0 0 0 0 0
0 0 0 0 81 0 0 0
0 0 0 0 0 0 0 81
0 0 81 0 0 0 0 0
Was it helpful?

Solution

for(int i = 0; i < a.length; i++)
{

    for(int j = 0; j < a[i].length; j++)
    {
        if (a[i][j]==1){

            System.out.print("Q");
            if(j < a[i].length - 1) System.out.print(" ");

        } else{
            System.out.print(a[i][j]);
            if(j < a[i].length - 1) System.out.print(" ");
        }
    }
    System.out.println();
}

Unless you need a "Q" stored in the array, can't you just print the "Q" out when needed...then it will show up in the results as you want.

OTHER TIPS

Use

System.out.print((char)a[i][j]);

instead of

System.out.print(a[i][j]);
for(int i = 0; i < a.length; i++)
{
   for(int j = 0; j < a[i].length; j++)
   {            
      if (a[i][j]==1){
           System.out.print('Q');
      }else{
           System.out.print(" ");
      }
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top