【问题标题】:Java method boolean returning false when it's supposed to be trueJava方法布尔值在它应该为真时返回假
【发布时间】:2014-12-10 00:33:34
【问题描述】:

我在一个班级里制作这个方法。我已经加倍检查了它,它应该相应地工作。当我使用这个方法在 main 方法中运行一个对象时,我总是得到一个错误的返回,即使它应该是真的。

打印语句不打印,所以我无法检查值是否正确传递,我还尝试让 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!");
    }

【问题讨论】:

  • 注意:忘了说 partDes 和 partCost 已经在 main 方法中初始化了
  • 如果你的打印语句没有被执行,还有其他完全错误的东西;那些是无条件的。我认为您的程序根本没有到达引用的块。
  • 是否打印“错误 - 提供的部件详细信息无效!”?
  • 是的,它会打印“错误 - 提供的零件详细信息无效!” !这太令人沮丧了!是的,如果方法中的打印语句没有打印,会出现什么问题?
  • 该方法是否在任何子类中被覆盖?

标签: java object methods boolean


【解决方案1】:

我相信你想用 ||而不是 |这里:

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

改成

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

| 用于按位或运算,而|| 用于条件或

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
  • 1970-01-01
  • 2021-08-09
  • 1970-01-01
  • 1970-01-01
  • 2014-04-10
  • 1970-01-01
相关资源
最近更新 更多