0

I have an array:

public String[][] bombBoard = new String[9][9];

This array is filled with values (*), however randomly throughout there are some other values (@).

Later in the program I want to tell the user how where the (@) is, if there are in the vicinity:

public void loadNumbers()
{
    try
    {
        if (bombBoard[bombRow][bombCol] == "@") 
        {
            System.out.println("You have landed on a bomb!");
            //break
        }
        else if (bombBoard[bombRow+1][bombCol].equals("@"))
        {
            System.out.println("There is a bomb in the vicinity!" + bombBoard[bombRow+1][bombCol]);
        }
        else if (bombBoard[bombRow-1][bombCol] == "@")
        {
            System.out.println("There is a bomb in the vicinity!" + bombBoard[bombRow-1][bombCol]);
        }
        else if (bombBoard[bombRow][bombCol+1] == "@")
        {
            System.out.println("There is a bomb in the vicinity!" + bombBoard[bombRow][bombCol+1]);
        }
        MORE CODE...
    }

}

It prints: "There is a bomb in the vicinity!@"

I want it to print "There is a bomb at 3, 2"

Probably so simple, but I'm drawing blanks. Instead of pulling back whats inside the element, I want the element index (I presume). Please halp!

1
  • 4
    Compare String values with String's equals method, not with the == operator. You did it correctly on the second condition. Commented Nov 14, 2013 at 19:47

2 Answers 2

1

I assume you just want to print out the coordinates of the @? If so you can do it like this:

System.out.println("There is a bomb at " + bombRow + ", " + bombCol + 1);

Use the same pattern for the other conditions. Also, you want to compare strings using .equals instead of == (the latter only compares references).

Sign up to request clarification or add additional context in comments.

3 Comments

This worked with a slight modification (instead of bombCol + 1, I used (bombCol + 1)) since it wasn't doing Math without the parens! Thanks.
I changed them all to == and it seems to work. How does .equals differ from == besides the obvious?
@RichardS I assume it works because of string interning. .equals will compare the actual String's contents whereas == only checks to see if they point to the same thing.
0

try

 System.out.println("There is a bomb in the vicinity!" + (bombRow+1).toString() +"," +bombCol.toString());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.