任何人都可以帮助我。我想通过方法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;
}
}
答案 0 :(得分: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 ;
}
希望这有帮助。
答案 1 :(得分:3)
假设Car
类有double getMaxSpeed ()
等方法,您可以按如下方式实现isFaster (Car otherCar)
:
boolean isFaster (Car otherCar) {
return this.getMaxSpeed() > otherCar.getMaxSpeed ();
}
答案 2 :(得分:0)
你必须根据速度覆盖 .equals()方法,然后才能有意义地比较你的对象。否则默认 .equals()使用 == 来比较对象,在这种情况下,对象只有在相同时才可以相等
答案 3 :(得分: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
}