【问题标题】:When I return an array, I'm getting a "cannot find symbol" error even though I have declared the array [duplicate]当我返回一个数组时,即使我已经声明了数组,我也会收到“找不到符号”错误 [重复]
【发布时间】:2022-02-05 00:17:58
【问题描述】:
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;

}

这是我正在创建的一个函数,它是我的 CS 课程的一个更大问题的一部分。我需要返回我声明的数组。但是,当我尝试编译时,出现错误:

BullsAndCows.java:94: error: cannot find symbol
         return count;
                ^
  symbol:   variable count
  location: class BullsAndCows

我已经搞砸了一段时间并在网上寻找答案,但似乎没有任何效果。

【问题讨论】:

  • 变量count的作用域只在“for”块内。您收到错误是因为您在块外使用该变量。

标签: java arrays compiler-errors return


【解决方案1】:

count 数组是在您的 for 循环内定义的,因此不能在它之外使用。

尝试修改你的代码为

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
}

如果我正确理解了您的代码逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 2016-06-19
    • 2022-11-03
    • 1970-01-01
    • 2016-03-04
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多