为什么这种方法不能“正常”?

时间:2016-10-02 00:41:33

标签: java recursion iteration

我正确地扫描了数字,但方法无法正常工作。第一个没有做任何事情,第二个进入无限循环。

调用的方法无法正常执行。我不知道该怎么做。

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()

1 个答案:

答案 0 :(得分: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“将”参数应用于函数;调用它“。

请注意,您不应仅仅为了踢腿而使用功能接口,因为它们可能会使代码不那么清晰。如果使用得当,它们可以使代码更多更简单;特别是与匿名函数配对时。