2016-01-29 153 views
2

我無法進行簡單的計數工作。現在,當我運行代碼時,不斷顯示0,我知道這是因爲我將計數設置爲0.但它應該顯示「Fizz」顯示的次數。爲什麼不計算任何東西?

我確定這很簡單,但我什麼都看不到!

public function __construct($firstParam, $secondParam, $firstSound = "Fizz", $secondSound = "Buzz", $numbers = 100) { 
     $this->firstParam = $firstParam; 
     $this->secondParam = $secondParam; 
     $this->firstSound = $firstSound; 
     $this->secondSound = $secondSound; 
     $this->numbers = $numbers; 
     $this->numsArray = $numsArray; 
    } 

    public function __toString() { 
     $count = 0; 
     for ($i = 0; $i < count($this->numsArray); $i++){ 
      $val = $this->numsArray[$i]; 
      if ($val == $this->firstSound) { 
       $count++; 
      } 
     } 
     $print = "Number of Fizzes: ".$count; 
     return $print; 
    } 

    public function execute() { 
     $this->numsArray = array(); 
     if ($this->secondParam > $this->firstParam) { 
      for ($i = 1; $i <= $this->numbers; $i++){ 
       if ($i % $this->firstParam == 0 && $i % $this->secondParam == 0) { 
        $this->numsArray[] = "\n".$this->firstSound.$this->secondSound."\n"; 
       } elseif ($i % $this->firstParam == 0) { 
        $this->numsArray[] = "\n".$this->firstSound."\n"; 
       } elseif ($i % $this->secondParam == 0) { 
        $this->numsArray[] = "\n".$this->secondSound."\n"; 
       } else { 
        $this->numsArray[] = "\n".$i."\n"; 
       } 
       echo $this->numsArray[$i-1]; 
      } 
     } else { 
      echo "\n".' First Number Bigger Than Second '."\n"; 
     } 
    } 
+0

計數($這個 - > numsArray)沒有正確評估。 檢查它的值並告訴我它說了什麼。 – penguin

+0

它說int(100) – Ale

+0

是numms數組填充隨機聲音Fizz和Buzz?如果Numsarray在索引0到99內沒有任何帶有Fizz的元素,那麼這將返回0. – penguin

回答

0

在你執行你不分配值numsArray [I]你也注入,將不匹配您檢查$ VAL正當平等的新行字符。另外我注意到你使用零索引來檢查他們和索引1來加載它。變更執行到:

for ($i = 0; $i < $this->numbers; $i++){ 
    if ($i % $this->firstParam == 0 && $i % $this->secondParam == 0) { 
     $this->numsArray[i] = $this->firstSound.$this->secondSound; 
    } elseif ($i % $this->firstParam == 0) { 
     $this->numsArray[i] = $this->firstSound; 
    } elseif ($i % $this->secondParam == 0) { 
     $this->numsArray[i] = $this->secondSound; 
    } else { 
     $this->numsArray[i] = $i; 
    } 
    echo $this->numsArray[$i]; 

這是PHP的一個更好的二進制字符串比較...

if (strcmp($val, $this->firstSound) == 0) 
+0

這沒有做任何不同的事情,和以前一樣。 – Ale

+0

numsArray的內容是什麼樣的? print_r($ this-> numsArray); – penguin

+0

[96] => 嘶嘶聲 [97] => [98] => [99] => 嘶嘶聲 )我認爲這也與 – Ale

相關問題