Reputation: 194
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 >.<
Upvotes: 0
Views: 1732
Reputation: 735
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++;
}
}
}
Upvotes: 0
Reputation: 3197
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.
Upvotes: 0
Reputation: 4608
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;
Upvotes: 2