简体   繁体   English

卡在FOR循环中

[英]stuck in FOR Loop

Base Car Class 基础车类

  1. current speed (property) – default value 0 当前速度(属性)–默认值0
  2. accelerate (method) 加速(方法)
  3. drive (method) 驱动器(方法)
  4. brand (property) - default value 'unknown' 品牌(属性)-默认值“未知”
  5. max speed (property) - default value 0 最大速度(属性)-默认值0

Camaro Car Class 卡玛洛汽车课

Inherits Base Car 继承基础车

  1. brand (property) - default value 'Chevy' 品牌(属性)-默认值“雪佛兰”
  2. max speed (property) – default value 200 最大速度(属性)–默认值200

Code Scenario: In this example I need to create an instance of Camaro and tell it to drive, I will assume it's moving in a straight line and there are no other driving factors. 代码场景:在此示例中,我需要创建一个Camaro实例并告诉它驱动,我将假定它沿直线运动并且没有其他驱动因素。 The car will accelerate until it hits its max speed. 汽车将一直加速直到达到最大速度。 It is required that drive will call accelerate. 要求驱动器将调用加速。 It is required accelerate will increment the current speed by 1. Once the Camaro reaches max speed it should stop accelerating and print that it hit the cars max speed. 要求加速将当前速度增加1。一旦Camaro达到最大速度,它应该停止加速并打印出达到汽车的最大速度。 The execution of drive should then also stop. 然后,驱动器的执行也应停止。

My Code is below which I tried where I am trying to print the speeds till it reaches the maximum.Where I should put the for loop to print all the speeds incremented by 1 till the max ie 100.Something like below 1 2 3 ...100 我的代码是下面,我尝试在哪里尝试打印速度,直到达到最大值。在这里,我应该将for循环打印所有递增1直到最大的速度,即100.Something类似于1 2 3 .. .100

<?php
class Car extends CI_Controller 
{

public $_speed = 0;
public $_brand = 'unknown';
public $_max = 0;

public function accelerate($_brand,$_max)
{
    if($this->_speed<=$_max)
    {
        for ($x = 0; $x <= 100; $x++)
        {
            $this->_speed += 1;
            return true;
        }
    }
    else
    {
        echo $this->_brand . 'Reached max speed';
    }

}

public function drive()
{
   $this->accelerate();
}

}
class Camaro extends Car
{
public $_brand = 'Chevy';
public $_max = 100;
}

$car1 = new Camaro();
echo $car1 -> accelerate($car1->_brand, $car1->_max);
?>
public function accelerate($_brand,$_max)
{
        for ($x = 0; $x <= 100; $x++)
        {
            $this->_speed += 1;
            if ($this->_speed ==$_max) {
                 echo 'max speed';
                 break; //use it to stop accelarating
            }
        }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM