Reputation: 495
I have the program Fibonacci which calculates and returns the Fibonacci number given by the user. However im not sure how to print out the returned value given by the method fibaux, for example output: fib 46 is 1836311903.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Fibonacci {
// main
public static void main(String[] args) {
try {
System.out.print("Enter number you would like to calculate ");
Scanner input = new Scanner(System.in);
int inputNumber = input.nextInt();
if (handleArguments(inputNumber)){
fib(inputNumber);
}
} catch (InputMismatchException exception) {
System.out.println("Input not an integer");
}
}
// Handle special case when n == 0
public static int fib(int n){
if(n == 0){
return 0;
}else{
int fibauxArray[] = fibaux(n);
return fibauxArray[0];
}
}
// Auxiliary function
// Return the nth and (n-1)th Fibonacci numbers
// n must be an integer >= 1
public static int[] fibaux(int n){
// base case for recursion
if(n == 1) {
return new int[] {1, 0};
// recursive case
}else{
int [] fibauxRecursive = fibaux(n - 1);
int f1 = fibauxRecursive[1];
int f2 = fibauxRecursive[0];
return new int[] {f1 + f2, f1};
}
}
static boolean handleArguments(int input) {
if (input >= 0 && input <= 46){
return true;
}else{
System.out.println("Error: number must be between 0 to 46");
return false;
}
}
}
Upvotes: 0
Views: 45
Reputation: 1707
int a=fib(inputNumber);
Call the function in this manner. Whatever value is returned by the function will be stored in variable a
.
To print the value:
System.out.println(a);
Look at the changes to be made:
public static void main(String[] args) {
try {
System.out.print("Enter number you would like to calculate ");
Scanner input = new Scanner(System.in);
int inputNumber = input.nextInt();
if (handleArguments(inputNumber)){
int a=fib(inputNumber); //value returned will be stored in a
System.out.println(a); //printing a
}
} catch (InputMismatchException exception) {
System.out.println("Input not an integer");
}
}
OR
Simply mention System.out.println(fib(inputnumber));
instead of fib(inputnumber);
Upvotes: 2
Reputation: 1957
Take a look at the method return type. I simply says it will return a int 'public static int fib(int n)
'. So no matter what will happen inside the method at the end of the day the method will return an int. So just assign it a new variable and print it out like following.
int returnVal =fib(inputNumber);
System.out.println(returnVal);
Upvotes: 0