首页 > 解决方案 > 在我的汽车类中通过布尔方法比较两个对象

问题描述

我在我的汽车课程中编写我的主要方法时遇到了麻烦。我的类代码编写如下;

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

我的问题是我在编写主要方法时遇到问题,我需要将我的“法拉利”汽车对象与“眼镜蛇”汽车对象进行比较。我需要使用 if/else 语句和方法 compare 来比较 ferrari obj 和 cobra obj。如果它们相同则需要输出“Same”,如果它们不同则需要输出“Different”。除了这个之外,我所有的其他方法都运行良好。

编辑:

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 类的对象 Car ferrari = 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 

`

标签: javaif-statementmethodsbooleancompare

解决方案


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

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 else 可以这样写,看起来会更好,

    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

推荐阅读