简体   繁体   中英

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!");
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM