使用递归时如何保持一致性?

时间:2012-05-07 01:05:15

标签: java recursion spell-checking

我正在编写一个拼写检查程序,我必须编写的一个函数必须找到拼写错误的单词的建议。因此,我正在使用递归来遍历我的基数树并找到所有建议。然而,当我的递归执行时,我使用的一个计数器不断增加,然后它减少,然后再次增加,当它实际上应该增加时。这是函数的代码。

    public void findSuggest(Edge tmp, String suffix, int app)
{
    int used = 0;

    if(tmp.tNode.children > 10)
    {
        used = 10;
    }
    else
    {
        used = tmp.tNode.children;
    }
    for(int j = 0; j < used; j++){
        if(app <= 9)
        {
            if((!"#".equals(tmp.prefix))&&(!"#".equals(tmp.tNode.edges[j].prefix))){
                suggest[app].append(tmp.prefix);                               
                suggest[app].append(tmp.tNode.edges[j].prefix);

                System.out.println("tmp.prefix: " + tmp.prefix);
                System.out.println("tmp.prefix............: " + tmp.tNode.edges[j].prefix);
                app++;     
                if(tmp.tNode.edges[j].tNode != null)
                {
                    suggest[app].append(tmp.prefix); 
                    System.out.println("App: " + app);
                    findSuggest(tmp.tNode.edges[j], suffix, app++);
                }
            }
        }
    }

}

这是我得到的输出: App是计数器,tmp.prefix是父节点的前缀,tmp.prefix .......是childs前缀。

  

App:0

     

tmp.prefix:t

     

tmp.prefix ............:e

     

App:1

     

tmp.prefix:e

     

tmp.prefix ............:s

     

App:2

     

tmp.prefix:t

     

tmp.prefix ............:我

     

App:3

     

tmp.prefix:i

     

tmp.prefix ............:c

     

App:4

     

tmp.prefix:c

     

tmp.prefix ............:al

     

App:5

     

tmp.prefix:i

     

tmp.prefix ............:se

     

App:6

     

tmp.prefix:se

     

tmp.prefix ............:d

     

App:7

     

tmp.prefix:se

     

tmp.prefix ............:s

     

App:7

     

tmp.prefix:i

     

tmp.prefix ............:ze

     

App:8

     

tmp.prefix:ze

     

tmp.prefix ............:d

     

App:9

     

tmp.prefix:ze

     

tmp.prefix ............:s

     

App:4

     

tmp.prefix:t

     

tmp.prefix ............:ure

     

App:0

     

tmp.prefix:x

     

tmp.prefix ............:e

     

App:1

     

tmp.prefix:e

     

tmp.prefix ............:d

     

App:2

     

tmp.prefix:e

     

tmp.prefix ............:s

     

App:2

     

tmp.prefix:x

     

tmp.prefix ............:ing

     

(这是所有单词建议的构建字符串数组的最终结果)

     

climatexe

     

climatesxed

     

climatiesxing

     

气候

     

climaicalture

     

climaise

     

climaised

     

climasesize

     

climaized

     

climazes

2 个答案:

答案 0 :(得分:1)

由于appint,因此它会按值传递,因此您在递归调用上对其所做的任何更改都不会在之前的调用中更改它。建议:将它改为你的类的静态或字段(取决于你需要的上下文,可能是一个fild),这样你就可以在所有的方法调用中拥有相同的应用实例

答案 1 :(得分:0)

在调用此方法之前,使用类级变量并将其初始化为零。根据您的需要,您可能会也可能不会选择静态使用。

相关问题