2016-10-02 41 views
0

我得到正確掃描的號碼,但方法不正確。第一個不做任何事,第二個陷入無限循環。爲什麼該方法沒有正確行事?

調用的方法執行不正確。我不知道該怎麼做。

import java.util.Scanner; 
public class testSequence { 

public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 
    System.out.println("Enter a number: "); 
    int enterNumber = scan.nextInt(); 
    System.out.println("1 for Iteration, 2 for Recursion: "); 
    int type = scan.nextInt(); 

    if (type == 1){ 
     computeIteration(enterNumber); 
    } else if (type == 2){ 
     computeRecursion(enterNumber); 
    } 
} 


public static int computeIteration(int enterNumber) { 
    int answer; 
    int multiplier = 1; 
    int count = 0; 
    int addend = 0; 
    if (enterNumber == 0) { 
     count++; 
     return enterNumber; 
    } else if (enterNumber == 1) { 
     count++; 
     return enterNumber; 
    } else { 

     for (int i = 0; i <= enterNumber; i++) {//need to adjust "i" for counter correction 

      enterNumber = (multiplier * 2) + addend; 
      addend = multiplier; 
      multiplier = enterNumber; 
      count += 1; 
     }//end for loop 
     answer = enterNumber; 
    }//end else 
    return answer; 
}//end computeIteration 

public static int computeRecursion(int n) { 
    int count = 0; 
    if (n == 0) { 
     count++; 
     return 0; 
    } else if (n == 1) { 
     count++; 
     return 1; 
    } else { 
     count++; 
     return computeRecursion(2 * (n - 1)) + computeRecursion(n - 2); 
    } 

}//end computerRecursion() 

}//end Sequence() 
+0

我看到你在調用'computeIteration',但是你不會對結果做任何事情。可能是問題的一部分? – ajb

+0

你在兩種方法的幾個地方增加了「數量」,但你不使用它。 – Murillio4

+0

Murillio4我知道,謝謝。我更關心該方法不正確的原因。 @ajb它應該返回答案,但答案根本不顯示。 – platypus87

回答

0

你永遠不會打印答案。

if (type == 1){ 
     computeIteration(enterNumber); 
    } else if (type == 2){ 
     computeRecursion(enterNumber); 
    } 

請注意您是如何調用函數的,但您從不對結果做任何事情。

你大概的意思是:

if (type == 1){ 
    System.out.println(computeIteration(enterNumber)); 
    } else if (type == 2){ 
    System.out.println(computeRecursion(enterNumber)); 
    } 

或者,如果你想獲得幻想:

UnaryOperator<Integer> f = 
    type == 1 ? 
     computeIteration 
     : computeRecursion; 

System.out.println(f.apply(enterNumber)) ; 

只是一個另外既然你問。我使用三元運算符,因爲我需要在兩件事情中進行選擇。在這樣的情況下,它比完整的if聲明更整潔。

UnaryOperator是一個功能接口。基本上,使用它們,你可以在一個變量內保存一個函數。在這種情況下,這是非常有用的,你希望在兩個簽名相同的函數(兩個函數都接受一個int並返回一個int)之間進行選擇,然後使用結果。

我將其中一個函數保存到f,然後通過編寫f.apply(9)apply「適用」參數;調用它)調用它。

請注意,您不應該僅僅使用功能接口來踢腿,因爲它們可能會使代碼更清晰。如果使用得當,他們可以使代碼更簡單;特別是與匿名功能配對時。

+0

這就是我做錯了。謝謝您的幫助!! – platypus87

+0

實際做的底部是什麼?這看起來比我見過的要先進得多(這不是很多),它看起來與我從「C」中作爲第三級操作員所瞭解的相似,我是否接近? – platypus87

+0

@ platypus87雅,三元運算符只是一個三元運算符。工作原理相同。我會稍微寫一下其他內容的快速描述。 – Carcigenicate

相關問題