Java 方法布尔值在应该为 true 时返回 false



我在一个类中创建这个方法。我已经仔细检查了一遍,它应该能正常工作。当我使用这个方法在main方法中运行一个对象时,我总是得到一个错误的返回,即使它应该是true。

print语句不打印,所以我无法检查值是否正确传递,我还尝试让if语句返回true,但它仍然返回false!它让我觉得一切都是逻辑正确的。

有没有一条规则我不知道,如果出现问题,布尔方法会自动返回false?

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

主要方法:

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

我相信您想在这里使用||而不是|:

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

将其更改为

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

|用于逐位OR运算,而||用于条件OR

最新更新