【问题标题】:looping and returning a array循环并返回一个数组
【发布时间】:2013-03-11 19:25:40
【问题描述】:

我需要一些帮助。我对actionscript很陌生,我想做的是从数组中计算苹果的数量,然后在主函数中跟踪它。现在我在返回时收到一个错误,该错误是 1067:将 String 类型的值隐式强制转换为不相关的 Number 类型。现在我试图切换数字和字符串,但我仍然得到错误。

public class extends Sprite
{

    public function()
    {
        var fruitNames:Array = ["apple", "peach","banana","pear","guava","apple","peach"];
        var totalApples:Number = countingApples(fruitNames);
        trace("You have " + totalApples);
    }

    private function countingApples(fruitNames:Array):Number
    {
        var total:String = "apple";

        for(var i:uint=0; i<7; i++)
        {
            total += Number[i];

        }
        return total;
    }

}

【问题讨论】:

  • 这是什么语言?
  • 你需要再看看你的countingApples 函数,它真的没有意义。你有一个设置为“apple”的String,然后在你的for循环中你有一个从0到6的uint。然后你试图将uint添加到String“苹果”。

标签: arrays actionscript return


【解决方案1】:

该错误是因为您试图返回total,这是一个String,但您已将countingApples 函数的返回类型设置为Number。这是一个可以满足您需求的示例,但我认为您应该再次尝试编写自己的版本,以便了解发生了什么:

private function countingApples(fruitNames:Array):Number
{
    var total:uint = 0;
    var targetFruit:String = "apple";
    var totalFruit:uint = fruitNames.length;

    for(var i:uint = 0; i < totalFruit; i++)
    {
        if (fruitNames[i] == targetFruit) {
            total++;
        }
    }

    return total;
}

【讨论】:

    【解决方案2】:
    public class extends Sprite
    {
    
        public function()
        {
            var fruitNames:Array = ["apple", "peach","banana","pear","guava","apple","peach"];
            var totalApples:Number = countingApples(fruitNames);
            trace("You have " + totalApples);
        }
    
        private function countingApples(fruitNames:Array):Number
        {
            var total:uint = 0;
    
            var i:String = new String();
            for(i in fruitNames) {
                if (fruitNames[i] == "apple") {
                    total = total + 1;
                }
            }
            return total;
        }
    
    }
    

    【讨论】:

    • 谢谢大家的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 2012-01-08
    • 2011-08-21
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多