If you're reading this, there's a pretty good chance that you have written a program/script/class/method/whatever involving the Fibonacci sequence. It's a great way to logic through a new language (after you've Hello Worlded, right?), and often it's a good intro into recursion. So this code likely won't be too unfamiliar to you:
public class fib {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Enter a number: ");
int num = scan.nextInt();
System.out.println(calculate(num));
}
private static int calculate(int n){
if (n <= 1)
return 1;
else
return calculate(n - 1) + calculate(n - 2);
}
}
We all know that Java is fairly verbose. So yeah, this isn't the shortest program ever (especially with the included boilerplate). But it's recursive and takes an input and does what we need it to do.
Комментариев нет:
Отправить комментарий