Monmon
Monmon

Reputation: 5

Java method boolean returning false when it's supposed to be true

I am making this method in one class. I have doubled checked it and all and it should work accordingly. When I run an object in the main method using this method I always get a false return even though it's supposed to be true.

The print statements don't print so I can't check whether the values are being passed in properly and I also tried making the if statement return a true as well and it still returns false! It doing my head in as everything is logically correct.

Is there a rule I don't know about where a boolean method will automatically return false if somethings wrong?

public boolean addPartsDetails (String newDescription, double newCost) {

  System.out.println("is description empty?: " + newDescription);
  System.out.println("is cost negative?: " + newCost);

  if (newDescription.isEmpty() | newCost < 0) {   
     return false;
  }

  else {
     this.partsCost += cost;
     String newPart = String.format("\t - %s (%.2f) \n", description, cost);
     this.partsList = this.partsList.concat(newPart);
     return true;
  }
 }

In main method:

 boolean addBool = tempObj.addPartsDetails(partDes, partCost);

    if(addBool) {
       System.out.println("\nPart details recorded sucessfullyfor vehicle \"" +     tempObj.getRegNum() + "\"");
    }
    else {
       System.out.println("\nError - invalid part details supplied!");
    }

Upvotes: 0

Views: 2209

Answers (1)

Juned Ahsan
Juned Ahsan

Reputation: 68715

I believe you want to use || instead of | here:

  if (newDescription.isEmpty() | newCost < 0) {   

change it to

  if (newDescription.isEmpty() || newCost < 0) {   

| is used for bitwise OR operation while || is used for conditional OR

Upvotes: 1

Related Questions