Because of a post I wrote back in February in which I used the calculation of a Fibonacci series to demonstrate some syntactic chicanery, I now seem to turn up quite a bit in searches along the lines of "How to calculate Fibonacci series in Java."
So why are people searching for this? Almost certainly because they're trying to cheat on their homework. The Fibonacci series is a nice simple problem to set to pupils to teach them about loops and so forth, and every year idle halfwits beg in the Sun Java Forums for solutions to be handed to them on a plate.
Well, my Continuations based solution would prove hilarious if anyone handed it in as homework. Even the most inattentive teacher would spot that one wasn't the pupil's own work. But to any beginner trying to learn something about the problem rather than trying to cheat, it would also be almost completely useless. How to find a happy middle ground?
The following piece of code is my attempt to square that particular circle. To any cheats out there, if you hand this in your teacher will know you have cheated. There are several peculiarities in the way I've written this that will really stand out to anyone reasonably familiar with Java.
To anyone just trying to understand how loops and conditions work, however, it should still stand up as a reasonable demonstration.
import java.math.BigDecimal; public class Fibonacci { public static void main(final String... args) { int count = 10; try { if( args.length > 0 ) { count = Integer.parseInt(args[0]); } if( count >= 0 ) { final BigDecimal[] fibonacci = { new BigDecimal(0), new BigDecimal(1) }; if( count > 0 ) System.out.println(0); if( count > 1 ) System.out.println(1); for( int index = 2; index < count; index++ ) { final BigDecimal sum = fibonacci[0].add(fibonacci[1]); System.out.println(sum); fibonacci[0] = fibonacci[1]; fibonacci[1] = sum; } } else { error(args[0]); } } catch( final NumberFormatException e ) { error(args[0]); } } private static void error(String param) { System.err.println("The only supplied parameter should be a positive integer"); System.err.print("for example 10, but you supplied: "); System.err.println(param); } }