我如何计算"计数"或者在比较迭代和递归方法时迭代或调用方法。

时间:2014-06-29 16:17:47

标签: java recursion methods iteration

我想编写一个程序来计算序列中的数字。并计算它被调用的次数。 我不知道如何在选择ietrative / recursive单选按钮时切换方法。我可以在主要使用if语句吗? 我评论了一些旧的错误,所以请忽略评论

类型Abstract Button中的方法addActionListener(ActionListener)不适用于参数(Sequence)LINE33

令牌上的语法错误,删除这些令牌.LINE17-Im我很确定我需要这个用于actionlistener

类型不匹配:无法从JTextField转换为double.LINE 46

令牌上的语法错误" double",@ expected- line 49

     package sequence;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

import javax.swing.*;

public class Sequence extends JFrame implements ActionsListener{
private static final double function=0;
private JTextField number=new JTextField(20),result=new JTextField(20),efficiency=new JTextField(20);
private static JRadioButton iterative= new JRadioButton("Iterative");JRadioButton recursive= new JRadioButton("Recursive");
private JButton compute = new JButton("Compute");


public Sequence(){
super (“Function Efficiency”);
setSize(350,250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout(6,2));
//add(new JLabel("Iterative Method"));add(form1);
ButtonGroup group = new ButtonGroup();
group.add(iterative);
group.add(recursive);

//add(new JLabel("Recursive Method"));add(form2);
add(new JLabel("Enter N"));add(number);
add(new JLabel(""));add(compute);
add(new JLabel("Result: "));add(result);
add(new JLabel("Efficiency :"));add(efficiency);
efficiency.setEditable(false);
compute.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
result.setText(result.getText());
efficiency.setText(number.getText());
//double efficiency=0;
}
private   double  iterativemethod (){number.getText();
if  (iterative.isSelected()) {
for(double i=1;i<=0;i++)
{
double result=Double.parseDouble(number.getText())*2+Double.parseDouble(number.getText());
}
return result;
}

private static  double  recursivemethod (){
    double number1=number.getText();
if (number1<=1)
return number1;
return recursivemethod(number-1);
}

}


public static void main(String[] args) {

    Sequence frame = new Sequence();
frame.setVisible(true);
if  (iterative.isSelected()) {

}
}

}

1 个答案:

答案 0 :(得分:0)

  • 您需要将字符串值解析为double
  • 递归方法需要缺少类型为double的参数

代码

private static  double  recursivemethod (double number){ // Add argument
    double number1=Double.pareseDouble(number.getText()); // Parse Double
    if (number1<=1)
       return number1;
    return recursivemethod(number-1);
}