数组列表元素相乘的java递归方法

fnatzsnv  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(442)

我希望我的措辞不要太混乱。我在学校做一个关于递归的项目。我构建了一个gui,允许用户在程序中输入数字。我想将用户输入textfield的数字存储在数组列表中,这样我就可以使用递归方法将所有数字相乘。我能够创建数组列表并存储数字,但我似乎不知道如何递归地将数组列表中的元素相乘。我想我可以这样做:

numbers.get(numbers.size()) * (numbers.size() - 1)

上述方法不起作用,因为索引总是越界。我也不太清楚这里发生了什么。
我有一个单独的驱动程序类,它调用gui类来运行程序。见下文。

public class Gui {
    final static boolean shouldFill = true;
    final static boolean shouldWeightX = true;
    final static boolean RIGHT_TO_LEFT = false;
    //Array list to store user input.
    public static List<Integer> numbers = new ArrayList<>();
    public static int num;
    //recursive Method
    public static int calculate(){

        return(0);
    }

    //Gui Program
    public static void addComponents(Container pane){
        if(RIGHT_TO_LEFT){
            pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        }

        JLabel label;
        pane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        if(shouldFill){
            c.fill = GridBagConstraints.HORIZONTAL;
        }
        //Instruction Label
        label = new JLabel("Welcome to recursion! Enter 5 numbers below.");
        if (shouldWeightX){
            c.weightx = 0.5;
        }
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 2;
        c.insets = new Insets(5, 10, 5, 10);
        pane.add(label, c);

        JLabel label1 = new JLabel("Enter Numbers:");
        c.gridx = 0;
        c.gridy = 1;
        pane.add(label1, c);

        JTextField tf = new JTextField();
        //Accepts only numbers 1 - 9. Zero defeats the purpose of the program.
        tf.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent ke) {
               tf.getText();
               if(ke.getKeyChar()>='1' && ke.getKeyChar()<='9' || ke.getKeyChar()== KeyEvent.VK_BACK_SPACE){
                   tf.setEditable(true);
               }else{
                   tf.setEditable(false);
                   label.setText("You must enter numeric digits 1-9");
               }
            }
        });
        c.gridx = 1;
        c.gridy = 1;
        c.insets = new Insets(0, 105, 0,10);
        pane.add(tf, c);

        JLabel outLabel = new JLabel(" ");
        c.gridx = 0;
        c.gridy = 4;
        c.gridwidth = 2;
        c.insets = new Insets(0,10,10,0);
        pane.add(outLabel, c);

        JButton b = new JButton("Submit");
        b.addActionListener(e -> {
            try {

                num = Integer.parseInt(tf.getText());
                numbers.add(num);
                outLabel.setText(String.valueOf(numbers));
                tf.setText("");

            }catch (Exception x){
                outLabel.setText("Please make sure you have entered a number!");
            }
        });
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 2;
        c.insets = new Insets(10,25, 10,25);
        pane.add(b, c);

        JButton b2 = new JButton("Multiply!");

        c.gridx = 0;
        c.gridy = 3;
        c.gridwidth = 2;
        c.insets = new Insets(0,25, 10,25);
        pane.add(b2, c);

    }

    public static void createGui(){
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("Recursive Multiplication");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addComponents(frame.getContentPane());
        frame.pack();
        frame.setVisible(true);
    }

}
tag5nh1u

tag5nh1u1#

首先,您必须创建乘法按钮的逻辑,例如:

JButton b2 = new JButton("Multiply!");
    b2.addActionListener(e -> {
        try {
            num = Integer.parseInt(tf.getText());
            int result = multiple_recursive(numbers, 0);
            // choose label to set the value.

        }catch (Exception x){
            // solve exception
        }
    });

然后定义递归乘法的方法:

public static int multiple_recursive(List<Integer> numbers, int count){
    if(numbers.size() == count){
        return 1;
    }
       return numbers.get(count) * multiple_recursive(numbers, count + 1);
}

所以你的想法是通过考试 list 和一个 count 变量。这个 count 将显示数字列表的当前位置。对于每个递归调用,从列表中获取当前元素 numbers.get(count) 再次递归调用,但将一个添加到当前 count 即。, multiple_recursive(numbers, count + 1); . 递归调用应该在当前 count 与列表大小相同,我们返回1,因为该值具有乘法标识属性。
对于包含元素的列表 {5, 2, 10} . 迭代如下:
numbers.size()==count假
返回numbers.get(0)多个递归(numbers,1);
返回5
(多个_递归(数字,1));
返回5*(numbers.get(1)multiple_recursive(numbers,2));
返回5
(2多个递归(数字,2));
返回5
(2*(numbers.get(2)multiple_recursive(numbers,3)));
返回5
(2*(10multiple_recursive(numbers,3)));
既然numbers.size()==count是真的
返回5
(2*(10*1));
返回50

相关问题