2013-03-22 130 views
0

我需要一些幫助。我對actionscript非常陌生,我想要做的是計算數組中的蘋果數量,然後在主函數中對其進行跟蹤。現在我得到一個返回錯誤,並且該錯誤是1067:隱式強制將字符串類型的值轉換爲不相關的類型數字。現在我試圖切換數字和字符串,但仍然出現錯誤。循環並返回一個數組

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; 
    } 

} 
+0

這是什麼語言? – Blender 2013-03-22 02:48:33

+0

你需要再次看看你的'countingApples'函數,它*真的*沒有意義。你有一個'String'設置爲「apple」,然後在'for'循環中你有一個從u到6的uint。然後你試圖添加'uint'到字符串「Apple」。 – 2013-03-22 21:51:20

回答

0
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; 
    } 

} 
+0

謝謝大家的幫助 – user2197182 2013-03-24 22:25:20

0

該錯誤是因爲你試圖返回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; 
}