更优雅的内部方法声明(没有所有杂乱)?

时间:2015-12-01 12:41:56

标签: java syntax inner-classes

我有一个递归方法,用一定的算法计算x ^ n,但这在这里并不重要。重要的是我的辅助函数,它跟踪该算法的递归调用。

public class FastPot {

    public static double fastPotRek(double x, int n) {
        class Aux {
            private double aux(double x, int n, int c) {
                if (n == 0) {System.out.print("It took "+c+" recursive calls to compute "); return 1;}
                else return (n % 2 == 0) ? aux(x*x, n/2, c+1)
                        : x * aux(x, n-1, c+1);
            }
        }
        Aux a = new Aux();
        return a.aux(x, n, 0);
    }
}

为了组织这一点,我想在aux内声明fastPotRek,为此你必须使用一个内部类,我的方法不能声明为静态。因此,我实例化了Aux a = new Aux();以便能够调用aux

请告诉我有一种方法可以让它更优雅,并告诉我我忽略了什么......就像蜂鸟能够以某种方式使aux静态或不需要实例化Aux

3 个答案:

答案 0 :(得分:3)

不需要内部类,也不需要使用静态类:

public class FastPot {
    //Static, use only from within FastPot
      private static double aux(double x, int n, int c) {
                if (n == 0) {
                  System.out.print("It took "+c+" recursive calls to compute "); 
                  return 1;
                } else {
                  return (n % 2 == 0) ? aux(x*x, n/2, c+1)
                        : x * aux(x, n-1, c+1);
                }
            }
    }

    //Your outward interface
    public static double fastPotRek(double x, int n) {
        return aux(x, n, 0);
    }
}

或者如果你坚持使用内部类:

public class FastPot {
    //Static, use only from within FastPot
    private static class Aux {
      private static double aux(double x, int n, int c) {
                if (n == 0) {
                  System.out.print("It took "+c+" recursive calls to compute "); 
                  return 1;
                } else {
                  return (n % 2 == 0) ? aux(x*x, n/2, c+1)
                        : x * aux(x, n-1, c+1);
                }
            }
    }


    //Your outward interface
    public static double fastPotRek(double x, int n) {
        return Aux.aux(x, n, 0);
    }
}

答案 1 :(得分:2)

我会发布这个答案,虽然很多人(包括我)对此不满意。请不要使用此类代码

public static double fastPotRek(double x, int n) {
    return new Cloneable() {
        private double aux(double x, int n, int c) {
            if (n == 0) {System.out.print("It took "+c+" recursive calls to compute "); return 1;}
            else return (n % 2 == 0) ? aux(x*x, n/2, c+1) : x * aux(x, n-1, c+1);
        }
    }.aux(x, n, 0);
}

同样,我强烈建议使用私有静态方法,如:

public static double fastPotRek(double x, int n) {
    return aux(x,n,0);
}
private static double aux(double x, int n, int c) {
    ...
}

答案 2 :(得分:0)

你有这个:

Aux a = new Aux();
return a.aux(x, n, 0);

我会这样写(也一样):

return new Aux().aux(x, n, 0);

编辑:我已完成StackOverflow。你们不想要帮忙吗?我不会放弃它。从现在开始,我只会询问我的问题,并且不会回答。