gpt4 book ai didi

Java比较两个字符串似乎不起作用

转载 作者:行者123 更新时间:2023-11-30 04:59:57 25 4
gpt4 key购买 nike

我得到了这个函数,它是一个私有(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 小车,因为列表中已经有该尺寸的汽车。

最佳答案

(我之前的答案是错误的 - 我匆忙中误读了代码......)

对于正在发生的事情,我只能想到一种解释:

You have called new Locations("Redfern") twice.

这可以解释为什么您会两次看到Car分配的Redfernsmall消息,以及为什么您没有看到hey

您可以通过在 Locations 构造函数中放置跟踪打印来确认这一点...

<小时/>

认为这是由 size 字符串之一上的前导/尾随空格引起的理论并不成立。如果这就是问题所在,当 checkCar 方法迭代 garage 列表时,OP 会看到 hey

关于Java比较两个字符串似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7136026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com