1

谁能帮我。我想通过一种方法比较两辆车是否更快isFaster(Car otherCar)。有人可以帮助我了解如何将Car对象与作为方法otherCar参数的对象进行比较isFaster。我怎样才能开始创建方法的主体。

public class Car {
  private String make ="";
  private int year = 0;
  private int maxSpeed = 0;

  public Car(String make,int year,int maxSpeed){
    this.make = make;
    this.maxSpeed = maxSpeed;
    this.year = year;
  }

  public void setSpeed(int maxSpeed){
    this.maxSpeed = maxSpeed;
  }

  public void setMake(String make){
    this.make = make;
  }

  public void setYear(int year){
    this.year = year;
  }

  public int getMaxSpeed(){
    return maxSpeed;
  }

  public int getYear(){
    return year;
  }

  public String getMake(){
    return make;
  }

  public String toString(double param){
    String temp = String.valueOf(param);
    return temp;
  }

  public String toString(int param){
    String temp = String.valueOf(param);
    return temp;
  }

  public String toString(char param){
    String temp = String.valueOf(param);
    return temp;
  }
}
4

4 回答 4

3

在 Car 对象中,它必须有一些属性,比如

class Car{

    int gear;
    double speed;
}

当你需要比较时,你需要决定,在决定属性上进行比较。

如果它的速度那么

// isFaster will only return true if the calling car object is faster 
// than the otherCar

// for your class this should work

isFaster(Car otherCar){       
    return this.getMaxSpeed() - otherCar.getMaxSpeed()  ;
}

// If you use double for speed, and you need precision
// you can set some tolerance value for comparisons.

isFaster(Car otherCar){       
    return (this.getMaxSpeed() - otherCar.getMaxSpeed() ) < TOLERANCE ;
}

希望这可以帮助。

于 2013-09-11T16:45:36.863 回答
3

假设Car该类有一个方法,例如double getMaxSpeed (),您可以实现isFaster (Car otherCar)如下:

boolean isFaster (Car otherCar) {
    return this.getMaxSpeed() > otherCar.getMaxSpeed ();
}
于 2013-09-11T16:46:23.820 回答
0

you have to override .equals() method based on speed then only you can compare your objects meaningfully. otherwise by default .equals() uses == to compare objects in this case objects can be equal only if they are same

于 2013-09-11T16:44:41.247 回答
0

创建这样的方法

public boolean isFaster(Car anotherCar){
   return this.maxSpeed > anotherCar.maxSpeed;
}

在客户端代码示例中:

public static void main(String args []){
  Car car1 = new Car();
  car1.setSpeed(200);// should be setMaxSpeed();
  Car car2 = new Car();
  car2.setSpeed(250);

  System.out.println(car1.isFaster(car2));// prints false

}
于 2013-09-11T16:52:37.883 回答