0

today i've occured some strange error, but i'll give my best to explain it because i can't solve it!

First of all thats the method which makes problems, BUT only after loading an object via FileInputStream!

The error is that it returns false instead of returning true, even when the searched object is in the saved array

    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;
}

When i'm loading an Object with the following method the upper method won't work : (i'm also saving this object with an similar way (write instead if load Object) )

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();
        }

Thats the Object i'm saving and loading:

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

And thats the "carInv" Array if this is important:

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

I apologize for this huge amount of code but i don't know where the error is, so i'm trying to give you all important information.

So thank you very much for reading all this, i hope you got an idea or solution for me.

Urbs
  • 131
  • 9

1 Answers1

2
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;
}

The issue was that you were not using the equals method for comparing String objects. Have a look at this post for further explanation

Community
  • 1
  • 1
Anton Belev
  • 11,963
  • 22
  • 70
  • 111