解决这个问题最好的方法是什么?
我们有一个羊场,有两台羊毛收集机。
年龄值和颜色值都是random.。
,
这只羊还没有准备好被剪掉。
我只是需要一些与合成的指导才能开始。谢谢!
发布于 2011-07-15 03:16:05
羊和机器是分开的物体。以下是一个开始:
class Sheep{
const COLOR_WHITE = 'white';
const COLOR_BLACK = 'black';
const AGE_YOUNG = 0;
const AGE_OLD = 1;
private $_color;
private $_age;
public static function makeRandom(){
$color = rand(0, 1)
? self::COLOR_WHITE
: self::COLOR_BLACK;
$age = rand(0, 1);
return new self($color, $age);
}
public function __construct($color, $age){
$this->_color = $color;
$this->_age = $age;
}
}
$sheep = Sheep::makeRandom();告诉我们你在更远的地方。
交换三元操作符:
// ...
if(rand(0, 1)){
$color = self::COLOR_WHITE;
}else{
$color = self::COLOR_BLACK;
{
// ...发布于 2011-07-15 03:14:15
这里有一些事情要做,但是您知道您需要$age和$color属性,以及读取这些属性的方法。很有可能,你不想写出来。
所以,我可能会:
getAge(){ return $this->age; }
getColor(){ return $this->color; }现在,您想要随机地分配颜色和年龄,这意味着您需要rand函数(还有其他选项,但rand会对您很好)。现在,如果我要这样做,我会将类似的内容放在构造函数中:
// assuming we're testing for male or female
// you really should look into why this works.
$this->gender = ( rand( 0, 1 ) )? self::MALE: self::FEMALE;
// notice the self::MALE and self::FEMALE? Those are class constants.
// http://php.net/manual/en/language.oop5.constants.php
// if you want to get this question *right* you'll need to look at those你的机器其实很简单。他们只测试每只羊的年龄是否足够被剪短,然后在此基础上增加一个计数器。
// assuming they are looking for a count of female sheep
// and state variables 'male' and 'female' which are initialized at 0
function processSheep( $sheep )
{
foreach( $sheep as $test )// stupid self-pluralizing nouns.
{
if( $sheep->getGender() == Sheep::MALE ) $this->males++;
else $this->females++; // obviously, you're going to need to swap
// out one of these increments for an echo.
}
}
function getNumberOfMales(){ return $this->males; }用两台机器计算出男性的数量:
$mach1->getNumberOfMales() + $mach2->getNumberOfMales();在n台机器中,男性的数量:
$males = 0;
foreach( $machs as $mach ){ $males += $mach->getNumberOfMales(); }发布于 2011-07-15 03:13:46
你的节目里有什么类型的东西?羊和机器。
绵羊和机器应该是同一类吗?那么,他们有相同的属性吗?机器有年龄吗?不是的。机器有颜色吗?不是的。那他们就不是同一个班了。
做一个羊类,给它年龄和颜色属性。类构造函数应该随机分配年龄和颜色属性的值,以便在创建每个绵羊对象时设置它们。
上一节机器课。它需要属性来保存多少黑色羊毛和多少白色羊毛收集。
为两个类中的属性创建setter和getter。
现在编写创建绵羊和机器对象的程序,并执行所需的任务。
https://stackoverflow.com/questions/6702215
复制相似问题