【问题标题】:Find out value that returns true from if statement -algorithm从 if 语句 - 算法中找出返回 true 的值
【发布时间】:2015-09-22 13:03:45
【问题描述】:

另一个类将向这个method(x,y,z) 传递随机数。我想知道boolean 确实从我最后的if() 语句返回true,所以我可以对其进行操作。我已经在 cmets 中解释了我的逻辑。

我还是很陌生,所以我的逻辑可能是错误的。

public static String FindDate(int x, int y, int z) {
    boolean istrue1 =(x >= 1 && x <= 31);
    boolean istrue2 =(y >= 1 && y <= 31);
    boolean istrue3 =(z >= 1 && z <= 31);
    if(istrue1 ^ istrue2){
        if(istrue1^istrue3){
            if(istrue2^istrue3){//now knowing that no values are the same, i can find the true value.
                if(istrue1||istrue2||istrue3){
                // I want to store/use/print/know which bool(istrue) that evaluated to true, so I would know if it is
                //x,y,z that went through the algorithm successfully.

                }
              }  else{return "Ambiguous";}


            }else{return "Ambiguous";}


        }else{return "Ambiguous";}
    return "true"; //I would actually end up returning the value that went through the algorithm
    }

【问题讨论】:

  • 返回 "true"inside 你的内部 if 条件。

标签: java algorithm sorting operators boolean-logic


【解决方案1】:

您可以像在 Java 中存储任何其他类型一样存储布尔值。我不确定您最后一条评论所说的“通过的价值”到底是什么意思,但是如果您想跟踪特定测试的结果,您不一定需要写类似

if (a == b) {
    return true;
} else {
    return false;
}

在这种情况下,

return a == b;

是等价的。如果表达式更复杂,括号是个好主意。

return ((a == b) || c);

您可以随时存储结果并在以后对其进行处理,而不是返回。

bool test = ((a == b) || c);
action(test);

【讨论】:

  • 存储价值是我所需要的。但我找不到动作(测试)?那是在java中吗?
  • action 可以是任何接受布尔值的方法。
【解决方案2】:

您可以执行以下操作:但是您的条件不正确 3 个变量的两个值 (true, false) 都不能不同。所以你的逻辑总是返回"Ambiguous"

 if(istrue1 ^ istrue2){
    if(istrue1^istrue3){
        if(istrue2^istrue3){
           //now knowing that no values are the same, i can find the true value.
           if(istrue1||istrue2||istrue3){
             // I want to store/use/print/know the bool that evaluated to true, so I would know if it is
            //x,y,z that went through the algorithm successfully.
            return "true";
      } 
 }     
return "Ambiguous";

【讨论】:

  • 好的,我知道我的逻辑会变得模棱两可。但无视这一点(稍后再处理)。语句是否返回“true”只是返回字符串,而不是真实的书?我知道导致 true 的实际布尔变量。
  • 所以你想知道 (istrue1||istrue2||istrue3) 中哪一个是真的?
  • 是的。确切地。我应该把它分成 3 个不同的 if 语句吗?
【解决方案3】:

代替:

if(istrue1||istrue2||istrue3)

将其分解为 3 个不同的 if 语句是最简单的。

if(istrue1)
if(istrue2)
if(istrue3)

没有我希望的简单技巧。不开心的一天。 我使用 xor(^) 运算符所做的语句也被证明是错误的逻辑。

这将是最简单的:

if(a&&b || a&&c || b&&c)

如果任何组合都为真,那将返回模棱两可。 然而,这不是最初的问题,但我想我不妨提一下。

【讨论】:

    猜你喜欢
    • 2016-02-12
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多