首页 > 解决方案 > 类未通过输入测试(作业帮助)

问题描述

我创建了一个类,它获取作物列表并返回任何特定作物的比率。它是这样使用的:

$cropRatio = new CropRatio;
$cropRatio->add('Wheat', 4);
$cropRatio->add('Wheat', 5);
$cropRatio->add('rice', 1);
echo "Wheat: " . $cropRatio->proportion('Wheat'); //Output: Wheat is .9

有了小麦和大米的这些值,答案就正确了。但是,我编写的类没有通过,因为系统说它在使用多种类型的输入进行测试时抛出异常。

作业软件给出这些错误:

  1. 示例案例:错误 - 分析您的代码将如何对不同的输入做出反应
  2. 几种作物:错误 - 分析您的代码将如何对不同的输入做出反应
  3. 只有一种作物:错误 - 分析您的代码将如何对不同的输入做出反应
  4. 零作物:错误 - 分析您的代码对不同输入的反应

我必须缺少几种类型的输入验证?

这是课程:

class CropRatio
{
   private $totalWeight;
   private $crops = [];

   public function add(string $name, int $cropWeight) : void
   {
       $name = ucfirst(trim($name));
       if(is_string($name) && is_int($cropWeight))
       {
           if(!array_key_exists($name, $this->crops)) {
               $this->crops[$name] = $cropWeight;
           }
           else
           {
               $this->crops[$name] += $cropWeight;
           }
           $this->totalWeight += $cropWeight;
       }
   }

   public function proportion(string $name) : float
   {
       if($this->totalWeight > 0)
       {
           return $this->crops[$name] / $this->totalWeight;
       }
       else 
       {
           return 0;
       }
       
   }
}

$cropRatio = new CropRatio;
$cropRatio->add('Wheat', 4);
$cropRatio->add('Wheat', 5);
$cropRatio->add('rice', 1);

echo "Wheat: " . $cropRatio->proportion('Wheat'); //Output: Wheat is .9

谁能指出为什么这个类没有通过输入测试?

标签: php

解决方案


主要问题是总重量,所以如果总重量不正确,那么您就无法计算比率。到目前为止,要解决此问题,您必须检查以前的作物重量并相应地修改当前作物重量和总重量

class CropRatio
{
    public $totalWeight;
    public $crops = [];

    public function add(string $name, int $cropWeight) : void
    {
  
        if(!array_key_exists($name, $this->crops)) {
            $this->crops[$name] = $cropWeight;
        }
        else 
        {
            $pre_weight = $this->crops[$name];  // this one was missing - very important
            $this->crops[$name] = $pre_weight + $cropWeight;
        }
 
        $this->totalWeight+=$cropWeight;
    }

    public function proportion(string $name) : Float
    {

        return $this->crops[$name] / $this->totalWeight;
    }
}

$cropRatio = new CropRatio;
$cropRatio->add('Wheat', 4);
$cropRatio->add('Wheat', 5);
$cropRatio->add('Rice', 1);


echo "Wheat: " . $cropRatio->proportion('Wheat');

推荐阅读