我编写了这个程序,用户输入斐波那契数列的第 n 项。因此,如果我输入 2,则会出现一条消息,表明 Fib 序列的第二项是 1。我还想输出数组的消息,直到他们输入的项。例如,用户输入 10,将出现一条消息,显示 fib 序列中第 10 项之前的所有数字。问题是我不知道该怎么做。它给了我一个奇怪的数字,比如@2235f23(类似的东西)。
我的代码:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.security.cert.X509Certificate;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class maincard extends JFrame{
JLabel label;
JTextField txf;
JButton calculate;
public static void main(String[] args){
new maincard();
}
public maincard(){
thehandler handler = new thehandler();
JPanel panel = new JPanel();
this.setSize(460, 360);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setTitle("Fibonachi Seqeuence");
this.add(panel);
label = new JLabel("Enter the nth term to find the value of the corresponding Fibonachi Sequence");
label.setToolTipText("What are you waiting for? Enter a damn number!!");
label.setVisible(true);
panel.add(label);
txf = new JTextField("Term");
txf.setSize(40, 25);
txf.addActionListener(handler);
txf.setVisible(true);
panel.add(txf);
calculate = new JButton("Calculate");
calculate.addActionListener(handler);
calculate.setSize(40, 60);
calculate.setVisible(true);
panel.add(calculate);
}
private class thehandler implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == calculate){
int fibTerm = Integer.parseInt(txf.getText());
int answer;
int[] x = new int[fibTerm];
x[0] = 0;
x[1] = 1;
for(int y = 2; y<x.length; y++){
x[y] = x[y-1] + x[y-2];
}
answer = x[fibTerm-1];
JOptionPane.showMessageDialog(null, "Sequence up to the " + fibTerm + "is: " + x);
JOptionPane.showMessageDialog(null, "The term is: " + answer);
}
}
}
}
哦,还有一个问题,发现第 n 个术语很有效,但我不明白为什么当我写 'answer = x[fibTerm-1]' 时它有效,但当我写 'answer=x[fibTerm]' 时它不起作用