Question

Before I state my question, I would like to thank everyone who helped me on my previous question. Anywho, I am currently getting the memory offsets as result even when I place it to the to a toString method. I've read most of the questions regarding the toString method and have somewhat of a understanding, I just wanted to make sure if I'm implementing this correctly. If you feel that this is a redundant question, I understand. Thanks for the help in advance.

Ship class

import java.util.Scanner;
public class Ship{

    int type;
    public String [][] shipPiece = new String[11][11];
    Scanner in = new Scanner(System.in);
    //Coordinate xy = new Coordinate();
    //private Coordinate[] bawdPiece = {new section()};
public Ship(){

}
    public String[][] placeShip()
    {
       System.out.println();
       for(int x = 1; x<10; x++)
       {
           for(int y = 1; y<10; y++)
           {
               shipPiece[x][y] = "0";
               System.out.print("|" + shipPiece);
           }
       }
       return shipPiece;
    }
    public String toString()
    {
        StringBuilder temp = new StringBuilder();

        temp.append(shipPiece);
        return temp.toString();
    }
Was it helpful?

Solution

public String toString()
{
    StringBuilder temp = new StringBuilder();

    for(int x = 0; x < 10; x++)
    {
       for(int y = 0; y < 10; y++)
       {
          temp.append(String.valueOf(shipPiece[x][y]);
       }
       temp.append("\n");
    }

    return temp.toString();
}

Also another thing I would like to point out is your array initialization. You initialize it with 11 x 11 indices, but your loop is only adding 9 values to each row and column Loop starts at 1 and ends at 9. You may want to fix your initialization to 10 x 10 and make your loop start at 0.

OTHER TIPS

If I understand the question correctly, you are trying to get the index of the shipPiece as a string?

If that's the case try String.ValueOf(index), you'll obviously have to do this twice as you have a 2-dimensional array.

Ex:

String s = String.ValueOf(xIndex) + "," + String.ValueOf(yIndex);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top