0

Below is my code:

public int maxTurns = 0;
public String[][] bombBoard = new String[9][9];

...

public void loadBombs()
{
    //loadArray();
    Random randomGen = new Random();
    for (int u=1; u<=9; u++)
    {
        int randomRow = randomGen.nextInt(9);
        int randomCol= randomGen.nextInt(9);
        bombBoard[randomRow][randomCol] = "@";
    }

    //counting @'s -- setting variable
    for (int d = 0; d < bombBoard[bombRow].length; d++)
    {
        for (int e = 0; e < bombBoard[bombCol].length; e++)
        {
            if (bombBoard[d].equals("@") || bombBoard[e].equals("@"))
            {
                maxTurns++;
            }
        }
    }

All I want to do is count the amount of (@)'s in the multidimensional array and assign it to a variable called maxTurns.

Probably very simple, just having a super hard time with it tonight. Too much time away from Java >.<

3 Answers 3

2

This line is equating the character @ with the entire dth row or eth row. Does not make sense really because an array row cannot equal to a single character.

if (bombBoard[d].equals("@") || bombBoard[e].equals("@"))

Instead, access a single cell like this

if (bombBoard[d][e].equals("@"))

And initialize maxTurns before counting i.e. before your for loop:

maxTurns = 0;
Sign up to request clarification or add additional context in comments.

3 Comments

Isn't the first line public int maxTurns = 0; initializing it?
Oh I missed that, but make sure before counting it must be zero, not changed by any other ways (e.g. in another method or even another class, because your field is public), or you will get wrong results!
Great. Thank you for your help. I will take a stab at it, and let you know my results.
0

You need to change the if codition

       if (bombBoard[d].equals("@") || bombBoard[e].equals("@"))

to

       if (bombBoard[d][e].equals("@"))

You are using 2D Array, and do array[i][j] can populate its value for a gavin position.

Comments

0

do you want to count from the whole array or certain parts of the array only?

From the code snippet you gave above, I can't really tell how you iterate the array since I'm not sure what is

bombBoard[bombRow].length  and  bombBoard[bombCol].length

But if you want to iterate the whole array, think you should just use:

for (int d = 0; d < 9; d++) // as you declared earlier, the size of array is 9
{
    for (int e = 0; e < 9; e++) // as you declared earlier, the size of array is 9
    {
        if (bombBoard[d][e].equals("@"))
        {
            maxTurns++;
        }
    }
}

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.