[英]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.当我使用这个方法在 main 方法中运行一个对象时,我总是得到一个错误的返回,即使它应该是真的。
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!打印语句不打印,因此我无法检查值是否正确传递,我还尝试使 if 语句也返回 true,但它仍然返回 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?如果出现问题,是否有我不知道布尔方法将在哪里自动返回 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;
}
}
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用于条件 OR
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.