/**
* LeonardoFibonacci.java
*
* Important Fibonacci calculating technology carefully crafted in October
* of 2001.
*
* Copyright 2001 by Matt Gerrans
*/
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;/**
* This craplet embodies the incredibly exciting and powerful
* Fibonacci-number-calculating technology that the world has
* been waiting for.
*/
public class LeonardoFibonacci extends JApplet
{
static final int START = 3;
static final int END = 49;
JTextField results = new JTextField(30);
JComboBox indexCombo = new JComboBox();
JLabel label = new JLabel( "Select the nth Fibonacci:" );
/**
* This is the garden variety applet initializer, obviously.
* It just sets up the UI with the appropriate controls and
* gives them the relevant information to display on start up.
*/
public void init()
{
for(int i = START; i <= END; i++)
indexCombo.addItem( (new Integer(i)).toString() );
results.setEditable(false);
indexCombo.addActionListener( new IndexComboListener() );
Container content = getContentPane();
content.setLayout(new FlowLayout());
content.add(results);
content.add(label);
content.add(indexCombo);
showResults( START );
}
/**
* Simple little class for monitoring the changes to the index
* choice combo box.
*/
class IndexComboListener implements ActionListener
{
/**
* @param e The event, which we'll just assume was a change to
* selection.
*/
public void actionPerformed(ActionEvent e)
{
showResults( indexCombo.getSelectedIndex() + START );
}
}
/**
* Shows the Fibonacci number for the selected index in a handsome text
* field.
* @param n The index of the Fibonacci that the user is interested in
* seeing.
*/
void showResults( int n )
{
long fibo = getNthFibonacci( n );
results.setText( "The " + n + (n==1?"st":(n==2?"nd":(n==3?"rd":"th"))) +
" Fibonacci number " + " is " +
addCommas( (new Long(fibo)).toString() ) + "." );
// (Yes, I know 1 and 2 can't be chosen, but this will continue
// work nicely even if the program is changed to allow them)
}
/**
* @param n The index position (starting from 1) of the Fibonacci number
* sought.
* @returns the nth Fibonacci number in the sequence (0, 1, 1, 2, 3...),
* where the 1st is 0, the 2nd is 1 and so on.
*/
public static long getNthFibonacci( int n )
{
if( n < 1 || n > END )
throw new IndexOutOfBoundsException();
long fibonacci = 1, prev = 0;
for( long i = 0; i < n; i++ )
{
fibonacci = prev + fibonacci;
prev = fibonacci;
}
return fibonacci;
}
/**
* @param num A string of digits.
* @returns The string of digits passed in with commas inserted for
* readability.
*/
public static String addCommas( String num )
{
boolean neg = num.substring(0,1).equals("-") ? true : false;
if(neg)
num = num.substring(1);
int len = num.length();
if( len > 3 )
{
int commaTime = 0;
for( int i = len; i > 0; i-- )
{
if( commaTime == 3 )
{
num = num.substring(0,i) + "," + num.substring(i);
commaTime = 0;
}
commaTime++;
}
}
return neg ? "-" + num : num;
}
}