The Fibbonacci Series
Write a program in an applet that enables a user to input an integer in a textfield and the applets indicates the ith Fibonacci number to calculate.
The Fibonacci series begins with 0 and 1 and has the property that each subsequent Fibonacci number is the sum of the previous two Fibonacci numbers.
The Fibonacci series may be defined recursively as follows:
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n-1) + fibonacci (n-2)
The Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FibonacciTest extends JApplet implements ActionListener {
JLabel numberLabel, resultLabel; //initialize variable for the gui
JTextField numberField, resultField;
//set up gui (Graphics User Interface)
public void init()
{
Container container = getContentPane();
container.setLayout(new FlowLayout());
//create numberLabel and attach it to the content pane
numberLabel = new JLabel ("Enter an integer and press Enter");
container.add(numberLabel);
//create numberField and attach it to the content pane
numberField = new JTextField(10);
container.add(numberField);
//register this applet as numberField's ActionListener
numberField.addActionListener(this);
//create resultLabel and attach it to the content pane
resultLabel = new JLabel("Fibonacci Value is");
container.add(resultLabel);
//create resultField and attach it to the content pane
resultField = new JTextField(15);
resultField.setEditable(false);
container.add(resultField);
}
//obtain user input and call method fibonacci
public void actionPerformed (ActionEvent event)
{
//Fibonacci numbers tend to become large quickly, therefore, we use long as the parameter type and return type of the Fibonacci.
long number, fibonacciValue;
//obtain user's input and convert to long
number = Long.parseLong(numberField.getText() );
showStatus("Calculating.........");
//Calculate fibonacci value for number input
fibonacciValue = fibonacci(number); //method fibonacci is called here
//indicate processing complete and display result
showStatus("Done!");
resultField.setText(Long.toString(fibonacciValue) );
}
public long fibonacci(long n) //Note n is the number chosen to represent number in method fibonacci(number);
{ //Note all method that has the arguments long, int, double, float must return its answer to the called method.
//base case
if(n== 0 || n == 1)
return n;
//recursive step
else
return fibonacci(n-1) + fibonacci(n-2);
}
}
0 comments :
Post a Comment