2015-09-30 32 views
2

嗨我試圖寫一個Java代碼的問題陳述:的StackOverflowError在尋找無可

找到沒有分發ň硬幣M個成員的方式,其中一人是隊長(分銷商)。每個會員可以一次拿1個硬幣,並將其傳遞給其他成員,包括隊長。船長不能擁有第一枚硬幣。但是,當只剩下一枚硬幣時,應該給上尉一枚硬幣。這可能有多少種方式?

我綁了這個。但得到StackOverflowError。請幫忙。

我在這裏開始做呼叫作爲解決(1,N)

private static int solve(int r, int n) 
    { 
     int count = 0; 
     if(n==2 && r!=1) 
     { 
      return 1; 
     } 
     if(n==2 && r==1) 
     { 
      return 2; 
     } 
     for(int i=1;i<=m;i++) 
     { 
      if(r!=i) 
      count += solve(i,--n); 
     } 
      return count; 
    } 

堆棧跟蹤

Exception in thread "main" java.lang.StackOverflowError 
    at NoPrey.solve(NoPrey.java:50) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java:62) 
    at NoPrey.solve(NoPrey.java: 
+0

想這是你的功課,你想,而你花時間在Facebook/Twitter要完成它。 –

+1

'for(int i = 1; i <= m; i ++)'你的方法中m是多少?你得到錯誤的r和n的值是多少? – YoungHobbit

+0

@Balwinder那不是我的功課先生,我正在學習java,並面臨一些問題.. @ YoungHobbit m是不。的成員 – Ashwani

回答

1

這只是幫助你理解錯誤。

發生這種情況是因爲n的值會變爲負數。只需在方法開始時輸入System.out.println(r + "\t\t" + n);並再次運行。 n=4m=3和初始值r=1。錯誤之前

public static void main(String[] args) throws FileNotFoundException { 
    solve(1, 4); 
} 

private static int solve(int r, int n) { 
    System.out.println(r + "\t\t" + n); 
    // rest of the code same. 

輸出:
1 4 2 3 1 2 3 1 1 0 2 -1 1 -2 2 -3 1 -4 2 -5 1 -6 2 -7 1 -8

+1

求解它。謝謝一噸:) – Ashwani

+1

是的..幫助追蹤錯誤。 – Ashwani