2015-12-01 13 views
1

我有一個遞歸的方法,用特定的算法計算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); 
    } 
} 

要組織多少有些我想聲明auxfastPotRek,爲此,你必須使用一個內部類,其方法我不能聲明靜態的。因此,我實例化Aux a = new Aux();以便能夠呼叫aux

請告訴我,有一種方法可以讓這個更優雅,讓我看到我忽略的東西......就像能讓aux靜止不動或不需要實例化Aux

+2

你可以做'Aux'靜態內部類'FastPot'或使用lambdas。除此之外,爲什麼你不使用正常的靜態方法?如果您嘗試組織代碼但以這種方式產生混亂,我不確定這種組織方式是否合理。 – Thomas

+3

我並沒有真正看到這裏的內部課程的重點。將'aux'方法作爲'private static'方法與'fastPotRek'相同的級別來完成這項工作。 – neomega

+0

我知道這看起來很糟糕,這就是爲什麼我問你是否可以嵌套在這種情況下,而不會陷入混亂:) – AleArk

回答

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) { 
    ... 
} 
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); 
    } 
} 
0

你有這樣的:

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

我會這樣寫(不變):

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

編輯:我已經完成了StackOverflow。你們不需要幫忙嗎?我不會放棄它。從現在開始,我只會問關於MY的問題,而不會回答。

+1

這不是真的回答這個問題;)這應該是一個評論,而不是一個答案! – ParkerHalo

+0

「請告訴我,有一種方法可以讓這個更加優雅,讓我看到我忽略的東西......就像beeing能夠以某種方式製作輔助靜態或不需要實例化Aux。」我的代碼沒有實例化輔助:) – Tuzane

+2

@Mayuso是的,它的確如此!有'new'關鍵字 – neomega

相關問題