platypus87 platypus87 - 2 months ago 8
Java Question

Why is the method not acting "properly?"

I get the numbers scanned in correctly, but the methods aren't working right. First one doesn't do anything and the second one goes into an infinite loop.

Method called is not performing correctly

enter code here
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()

Answer

You're never printing the answer.

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

Note how you're calling the functions, but you never do anything with the result.

You probably meant:

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

Or, if you wanted to get fancy:

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

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