为什么不能进入"如果"?

时间:2015-11-21 21:57:35

标签: java tree

我试图在树中寻找一个整数,这是方法的代码: 该方法应该搜索树中的所有节点,并在找到整数时返回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;
   }

问题在于,由于某种原因,他们不会进入"如果"测试是否存在整数,打印显示:

 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

提前致谢!

2 个答案:

答案 0 :(得分:0)

你的问题是它可能正在进入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;
   }

如果你想缩短它以删除print语句。

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

答案 1 :(得分:0)

if语句 已输入您永远不会对该语句中设置为true的resp执行任何操作。我想您想要做的就是在找到true后立即返回no.elemento.getProbMandante() == x,而不是仅设置resp = true return true。如果您只在树中搜索一个特定节点,则根本不需要resp

如果您没有找到这样的节点(您目前的情况是return resp),则可以返回false。 (即使您找到节点,当您的方法返回resp不是true的原因是它是一个以resp作为局部变量的递归方法。 )