2015-08-09 32 views
-2

我想打印变量count的最终值,但是当我在countTrees方法中使用此方法时,它也会打印中间值。我的主要方法无法访问count。我不想改变返回变量如何将变量的方法应用到主要方法中

public class treecount { 
    public static void main(String[] args){ 
     countTrees(3); 
     //System.out.println(countTrees(3)); 
     //System.out.println(count); 
    } 
    public static int countTrees(int numKeys) { 
     //int temp = 0; 
      int count = 0; 
      if (numKeys <=1) { 
       count += 1; 
      return(1); 
      } 
      else { 
      int sum = 0; 

      int left, right, root; 

      for (root=1; root<=numKeys; root++) { 
       left = countTrees(root-1); 
       right = countTrees(numKeys - root); 

       // number of possible trees with this root == left*right 
       sum += left*right; 
       count += root*left*right; 

      } 
      System.out.println(count); 
      return(sum); 
      } 
    } 

} 

输出:

3 
3 
10 

输出所需:

10 

嘿,伙计们帮我解决这个问题thanx提前

回答

1

我发现了一个方式变量 - 有点变通方法,但它是一个疯狂的递归丛林那里......

布尔internal信号如果功能已经从其内部或外部调用,从而确定计算是否完成,在这种情况下将count返回给外部调用者,而不是自己的sum

public static void main(String[] args){ 
//  countTrees(3, false); 
     System.out.println(countTrees(3, false)); 
     //System.out.println(count); 
    } 
    public static int countTrees(int numKeys, boolean internal) { 
     //int temp = 0; 
      int count = 0; 
      if (numKeys <=1) { 
       count += 1; 
      return(1); 
      } 
      else { 
      int sum = 0; 

      int left, right, root; 

      for (root=1; root<=numKeys; root++) { 
       left = countTrees(root-1, true); 
       right = countTrees(numKeys - root, true); 

       // number of possible trees with this root == left*right 
       sum += left*right; 
       count += root*left*right; 

      } 
//   System.out.println(count); 
      if(internal)return(sum); 
      else return count; 
      } 
    } 
0

你'在正确的轨道上,试试这个:

删除System.out.println(count);从计数树方法(因为这就是为什么它多次打印出

在main方法中,使用的System.out.println(countTrees(3));你之前注释掉

注意:你返回,而不是在countTrees方法

+0

不,这会打印变量总和的值,在这种情况下是5。我想要的是打印值varable count –