'When I return an array, I'm getting a "cannot find symbol" error even though I have declared the array [duplicate]
public static int [] tallyResults (String number, String guess)
{
int bulls = 0;
int cows = 0;
for (int i=0;i<number.length();i++)
{
if (number.charAt(i)==guess.charAt(i))
{
bulls = bulls + 1;
}
else if (contains(number, guess.charAt(i)))
{
cows = cows + 1;
}
else
{
continue;
}
cows = cows - bulls;
int [] count = {bulls, cows};
}
return count;
}
This is a function I'm creating that's part of a larger problem for my CS class. I need to return the array that I declared. However, when I attempt to compile, I get an error:
BullsAndCows.java:94: error: cannot find symbol
return count;
^
symbol: variable count
location: class BullsAndCows
I've messed around with it for a bit and looked online for answers, but nothing seems to do the trick.
Solution 1:[1]
The count array is defined inside your for loop and thus it cannot be used outside of it.
Try to modify your code as
public static int [] tallyResults (String number, String guess)
{
int bulls = 0;
int cows = 0;
for (int i=0;i<number.length();i++)
{
if (number.charAt(i)==guess.charAt(i))
{
bulls = bulls + 1;
}
else if (contains(number, guess.charAt(i)))
{
cows = cows + 1;
}
else
{
continue;
}
cows = cows - bulls;
}
return new int[]{bulls, cows}; //count
}
If I correctly understand the logic of your code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
