通过java Applet输出第n个斐波那契序列数!
编译工具eclipse +jdk
import java.applet.Applet;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AppletInOut extends Applet implements ActionListener {
Label prompt = new Label("输入要计算的第几个斐波那契序列数:");
TextField input = new TextField(5);
Button btn = new Button("计算");
int n = 1;
long fib = 0;
public void init(){
add(prompt);
add(input);
add(btn);
btn.addActionListener(this);
}
public void paint(Graphics g){
g.drawString("斐波那契序列第"+ n +"个数据是"+fib, 10, 50);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
n = Integer.parseInt(input.getText());
fib = Fibonacci(n);
repaint();
}
long Fibonacci(int n){
if(n==1||n==2)
return n-1;
else
return Fibonacci(n-1)+Fibonacci(n-2);
//递归调用计算斐波那契数
}
}
程序运行效果: