我编写了一个在arralist中搜索对象的方法,但是我需要此搜索采用两个参数并将它们与对象的描述进行比较。让我感到困惑的是,我不知道如何使我的方法采用两个参数,并将这两个参数与一个描述进行比较。 例如对象描述:Blue Mustang
现在搜索方法必须采用两个参数,在这种情况下,一个字符串“Blue”和一个字符串“Mustang”,我不知道如何做到这一点。我找到了一种方法,只需将完整的描述写为一个参数,并且效果很好。我将保留我尝试更改以查找两个参数的方法,以及采用一个参数并且工作正常的方法。值得一提的是,该方法还需要寻找未租借的汽车,这就是为什么还要与租赁日期进行比较,因为如果汽车是租借的,则将有一辆,如果不是,则不会。
尝试更改它以查找两个参数:
public Car searchCar(String description, String description2)
{
for (Car car : cars) {
if (car.getDescription().equals(description) && car.getDescription().equals(description2) && car.getHireDate().equals("")) {
System.out.println( ": " + car.getDescription() + " rate: £" + car.getDailyRate() + " Down payment: £"+ car.getDownPayment());
return car;
}
else if (car.getHireDate() != ("")) {
System.out.println("This car is rented!!");
}
else {
}
}
return null;
}
这是一个只需要一个参数并且工作正常的:
public Car searchCar(String description)
{
for (Car car : cars) {
if (car.getDescription().equals(description) && car.getHireDate().equals("")) {
System.out.println( ": " + car.getDescription() + " rate: £" + car.getDailyRate() + " Down payment: £"+ car.getDownPayment());
return car;
}
else if (car.getHireDate() != ("")) {
System.out.println("This car is rented!!");
}
else {
}
}
return null;
}
最佳答案
描述需要与描述2相同 你可以这样做:
String fulldescription=description+" "+description2;
然后
if (car.getDescription().equals(fulldescription)...
可以采用不同的方法
if (car.getDescription().indexOf(description)>0 && car.getDescription().indexOf(description2)>0 )...
关于java - 搜索对象数组列表困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8606070/