【发布时间】:2011-10-31 10:49:00
【问题描述】:
我得到了这个函数,它是一个private boolean 函数,它检查车库内是否已经有一辆相同大小的汽车。如果没有,我将它添加到arrayList,我之前创建了一个printList() 类型函数来遍历arraylist 并打印出值(完美运行)但不知何故我的private boolean 函数没有似乎完全有效。
这是我的代码:
public class Cars {
public Cars (String size, boolean booking) {
this.carSize = size;
this.isBooked = booking;
}
public String getSize() {
return this.carSize;
}
public boolean checkBook () {
return this.isBooked;
}
private String carSize;
private boolean isBooked;
}
public class Locations {
public Locations (String curLocation) {
garage = new ArrayList<Cars>();
location = curLocation;
}
public void addCar (String size, boolean booking) {
if (garage.isEmpty() || !checkCar(size)) {
garage.add(new Cars(size, booking));
System.out.println("Car assigned " + location + " " + size);
}
}
private boolean checkCar (String size) {
for (Cars car : garage) {
System.out.println("hey");
if (size.equals(car.getSize())) return true;
}
return false;
}
private ArrayList <Cars> garage;
private String location;
}
输入如下:
Car small City
Car small Redfern
Car small Redfern
输出:
Car assigned City small
Car assigned Redfern small
Car assigned Redfern small
它不应该打印出第二个 Redfern small,因为列表中已经有那个尺寸的汽车了。
【问题讨论】:
-
顺便说一句,
Cars类不应该是复数。 -
没有看到你的主要方法很难说它有什么问题。也许你在第三行有多余的空格?你能在相等比较之前修剪它吗?
标签: java arraylist variable-assignment