在我的汽车类中通过布尔方法比较两个对象

时间:2018-10-25 04:58:36

标签: java if-statement methods boolean compare

我无法在汽车课上编写主要方法。我的课程代码如下所示;

public boolean compare (Car otherCar) {
    return (model.equals(otherCar.model) && year == otherCar.year);
} 

我的问题是我在编写主要方法时遇到麻烦,我需要将“法拉利”汽车对象与“眼镜蛇”汽车对象进行比较。我需要使用一条if / else语句,并将方法进行比较以将法拉利obj与 眼镜蛇如果相同,则需要输出“相同”,如果不同则需要输出“不同”。除此方法外,我所有其他方法都工作正常。

编辑:

private String model;
private int year;

// default constructor
public Car()
{
    model = "NA";
    year = 0;
}

// overloaded constructor
public Car (String newModel, int newYear)
{
    model = newModel; 
    year = newYear;
}

// mutator methods
public void setModel (String newModel)
{
    model = newModel;
}

public void setYear (int newYear)
{
    year = newYear;
}

// accessor methods
public String getModel()
{
    return model;
}

public int getYear()
{
    return year;
}

public boolean compare (Car otherCar)
{
    return (model.equals(otherCar.model) && year == otherCar.year);
} 

public void print()
{
    System.out.println(model + " (" + year + ")");
}
}

我的问题是我应该如何在我的main方法中编写if-else语句以使用compare方法比较这两个对象

编辑2:`{
         //创建名为Ferrari的Car类的对象          法拉利汽车= new Car();

     // Use the print method to print all information about the ferrari object.
     ferrari.setModel("Ferrari");
     ferrari.setYear(2010);
     ferrari.print();
     // Create an object of the class Car named cobra, passing parameters "Cobra" and 1967.
     Car cobra = new Car("Cobra", 1967);

     // Print information about the Cobra object using get methods.
     System.out.println(cobra.getModel() + " " + cobra.getYear());

     // Change the model of the cobra object to "Shelby Cobra".
     cobra.setModel("Shelby Cobra");

     // Change the year of the cobra object to 1963.
     cobra.setYear(1963);


     System.out.println(cobra.getModel() + " " + cobra.getYear());

     // Use an if/else statement and the compare method to compare the ferrari obj with the 

`

1 个答案:

答案 0 :(得分:0)

在您的主要方法中,您可以简单地编写if来比较汽车并像这样打印出来,

if (ferrari.compare(cobra)) {
    System.out.println("Both cars are same.");
} else {
    System.out.println("Both cars are different.");
}

另一个要点,对于打印对象值,您最好重写toString()方法,以免像您那样实现print()方法。您可以像这样实现toString方法,

public String toString() {
    return String.format("model: %s, year: %s", model, year);
}

然后您的if if可以这样写,看起来会更好,

    if (ferrari.compare(cobra)) {
        System.out.println("("+ferrari + ") AND (" + cobra + ") cars are same");
    } else {
        System.out.println("("+ferrari + ") AND (" + cobra + ") cars are different");
    }

哪个将给出以下输出,

(model: Ferrari, year: 2010) AND (model: Shelby Cobra, year: 1963) cars are different