2014-10-03 72 views
0

我試圖計算使用2種不同的方法,一種遞歸Fibonacci序列和使用循環的其他。如果要求用戶輸入數字,我很難確定如何確定每種方法的限制。這裏是我的代碼:JAVA堆棧溢出發生之前確定的極限,斐波那契序列

import java.util.Scanner; 
public class Recursion { 

public static void main(String[] args) 
{ 
    Scanner kb = new Scanner(System.in); 
    long n, result1, result2, startTime1, stopTime1, startTime2, stopTime2; 

    System.out.println("Please Enter A Number in between 0 and maxValue, will be calcualtred using 2 methods...."); 
    n = kb.nextLong(); 

    startTime1 = System.nanoTime(); 
    result1 = fibRecursive(n); 
    stopTime1 = System.nanoTime(); 

    startTime2 = System.nanoTime(); 
    result2 = fibLoop(n); 
    stopTime2 = System.nanoTime(); 

    System.out.println("\nDisplaying solution for recursive method: "+ result1 + " Time Taken (in nanoseconds): " + (stopTime1 - startTime1)); 
    System.out.println("\nDisplaying solution for loop method: "+ result2 + " Time Taken (in nanoseconds): " + (stopTime2 - startTime2)); 
    System.out.println("\nThanks for using our fibnoacci calculator. "); 
} 

public static long fibRecursive(long i) 
{ 
    if(i == 0) 
     return 0; 
    else if(i == 1) 
     return 1; 
    else 
     return fibRecursive(i - 1) + fibRecursive(i - 2); 
} 
public static long fibLoop(long k) 
{ 
    long a = 0, b = 1, ans = 0; 
    if(k == 0) 
     return 0; 
    else if(k == 1) 
     return 1; 
    else 
    for(int i = 1; i < k; i++) 
    { 
     ans = a + b; 
     a = b; 
     b = ans;  
    } 
    return ans; 
} 
+1

你嘗試過用映入'StackOverflowError' – 2014-10-03 19:54:05

+0

並不知道任何這 – lucyb 2014-10-03 20:40:48

回答

0

另一種方法可以嘗試捕捉錯誤。

try { 

} catch(StackOverflowError e){ 
     System.err.println("ouch!"); 
} 
+0

怎麼做這項工作完全是一個try/catch塊周圍的遞歸方法? – lucyb 2014-10-03 20:41:09

+1

具有非遞歸的方式來解決這個問題,我認爲是最好的(人大多數在Java),但如果你需要的算法之間進行切換,你可以使用try圍繞/搭上調用* fibRecursive *如果拋出的錯誤調用* fibLoop *。 – Joselo 2014-10-04 00:50:55

+0

進出口仍然實現了我的代碼這個問題,並且我得到了一堆錯誤,說的StackOverflowError dosent的存在(紅色線) – lucyb 2014-10-04 13:57:51