为什么不输入"if"?

Why won't enter the "if"?

我试图在树中寻找一个整数,这里是该方法的代码: 该方法应该搜索树中的所有点头,然后找到整数 return true。

   private boolean mostrarCentral(No2 no, double x) {
      boolean resp =false;

      if (no != null) {

        mostrarCentral(no.esq,x); // Elementos da esquerda

        System.out.println(" No is " + no.elemento.getProbMandante() + " |x is " + x);

       if(no.elemento.getProbMandante() == x){
                resp = true;
         }

        mostrarCentral(no.dir,x); // Elementos da direita.

      }
      return resp;
   }

问题是由于某种原因不会输入 "if" 测试整数是否存在,打印显示如下:

 No is 60.0 |x is 15.1
 No is 45.4 |x is 15.1
 No is 60.7 |x is 15.1
 No is 30.5 |x is 15.1
 No is 75.9 |x is 15.1
 No is 60.2 |x is 15.1
 No is 45.9 |x is 15.1
 No is 45.7 |x is 15.1
 No is 60.1 |x is 15.1
 No is 60.0 |x is 15.1
 No is 15.1 |x is 15.1
 No is 30.0 |x is 15.1
 No is 30.0 |x is 15.1
 No is 30.4 |x is 15.1
 No is 45.1 |x is 15.1
 No is 60.3 |x is 15.1
 No is 60.8 |x is 15.1
 Don't exist

提前致谢!

您的问题是它可能正在进入 if,您只是没有返回结果。我想这样的事情会奏效。

   private boolean mostrarCentral(No2 no, double x) {
      boolean resp =false;

      if (no != null) {

        resp = resp || mostrarCentral(no.esq,x); // Elementos da esquerda

        System.out.println(" No is " + no.elemento.getProbMandante() + " |x is " + x);

       if(no.elemento.getProbMandante() == x){
                return true;
         }

        resp = resp || mostrarCentral(no.dir,x); // Elementos da direita.

      }
      return resp;
   }

如果你想缩短它来删除打印语句。

   private boolean mostrarCentral(No2 no, double x) {
      if (no != null) {
        return no.elemento.getProbMandante() == x || 
                    mostrarCentral(no.esq,x) || 
                    mostrarCentral(no.dir,x);
      }
      return false;
   }

if 语句 输入的 但是 你永远不会对你设置为 true 的 resp 做任何事情在该声明中。我猜你想要做的是 return true 一旦你找到 no.elemento.getProbMandante() == x,所以不要设置 resp = true 而是 return true。如果您只是在树中搜索 一个 个特定节点,则根本不需要 resp

如果您没有找到这样的节点(您目前return resp就是这种情况),您可以return false代替。 (为什么 resp 不是 true 当你的方法 returns 即使你找到一个节点 是因为它是一个递归方法 resp 作为局部变量。)