Arraylist搜索和显示对象方法混淆

时间:2011-12-19 21:08:33

标签: java methods arraylist

这两个方法需要考虑来自第二个名为car的类的boolean onLoan才能应用它们,我的意思是只考虑onLoan == false的汽车。我到了他们的基地尝试了我想到的解决这个问题,但对我来说似乎没有什么工作似乎有一些建议吗?谢谢!

/**
 * Constructor for objects of class RentalCompany
 */
public void showAllCarsNotOnloan ()
{
    for ( Car car:cars) { 

    if (cars.size()>0 ) {

        int i = 0;
        System.out.println(car.getDescription());
        i++;

    }
    else if ( cars.size() < 0 ){
        System.out.println ("Add cars first");
    }
   }
}

和第二种方法

public Car searchCar(String description)
{
    for (Car car : cars) {
        if (car.getDescription() == description) {
            return car; 
        }
        else {
            System.out.println("This car is not listed. Retry!!");
        }
    }
    return null;
}

1 个答案:

答案 0 :(得分:0)

以下将完成工作:

Car类:

public class Car {
    private boolean onLoan;
    // Other variables...

    public boolean isOnLoan() {
        return onLoan;
    }
    // Other methods....
}

现在,showAllCarsNotOnloan方法

public void showAllCarsNotOnloan() {
    if (cars.size() == 0) {
        System.out.println("Add cars first!");
        return;
    }

    for (Car car : cars) {
        if (!car.isOnLoan()) {
            System.out.println(car.getDescription());
        }
    }
}

searchCar方法

public Car searchCar(String description) {
    for (Car car : cars) {
        if (car.getDescription().equals(description)) {
            return car;
        }
    }

    System.out.println("This car not listed. Retry!!");
    return null;
}