gpt4 book ai didi

java - 保存和加载对象后,If-Method 返回错误值

转载 作者:行者123 更新时间:2023-12-02 02:50:31 25 4
gpt4 key购买 nike

今天我遇到了一些奇怪的错误,但我会尽力解释它,因为我无法解决它!

首先,这个方法会产生问题,但只有在通过 FileInputStream 加载对象之后!

错误在于它返回 false,而不是返回 true,即使搜索到的对象位于已保存的数组中

    public boolean isCarOwned(String pName) {   //find Car in Array with pName
for(int x = 0; x < carCount; x++) { // carCount = array length
if(carInv[x] != null) { //check if array is empty
if(carInv[x].getName() == pName) { //check if car in array has pName
return true;
}
}
}
return false;
}

当我使用以下方法加载对象时,上面的方法将不起作用:(我也用类似的方式保存该对象(如果加载对象则改为写入))

ObjectInputStream invLoad;
try {
invLoad = new ObjectInputStream(new FileInputStream("save/inv_data.bin"));
Main.inv = (Inventory) invLoad.readObject();
invLoad.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}

这就是我正在保存和加载的对象:

 public Car(String pName, int pSpeed, int pSpace, int pPrice, String pCarIcon) {
name = pName;
speed = pSpeed;
space = pSpace;
price = pPrice;
carIcon = new ImageIcon(pCarIcon); }

如果这很重要的话,那就是“carInv”数组:

private Car carInv[] = new Car[10];

对于如此大量的代码,我深表歉意,但我不知道错误在哪里,所以我试图向您提供所有重要信息。

非常感谢您阅读所有这些内容,我希望您能为我提供一个想法或解决方案。

最佳答案

public boolean isCarOwned(String pName) {   //find Car in Array with pName
for(int x = 0; x < carCount; x++) { // carCount = array length
if(carInv[x] != null && carInv[x].equals(pName)) { // if x-th value is not null and is equal to pName
return true;
}
}
return false;
}

问题在于您没有使用 equals 方法来比较 String 对象。看看这个post进一步解释

关于java - 保存和加载对象后,If-Method 返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43913147/

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