1

I hope my wording isn't too confusing. I'm working on a school project regarding recursion. I built a GUI to allow a user to input numbers into the program. I want to store the numbers the user enters into the textField in an array list so that I can use a recursive method to multiply all numbers by themselves. I am able to create the array list and store the numbers, but I can't seem to figure out how to recursively multiply the elements in the ArrayList. I thought I could do something like this:

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

The above doesn't work because the index is always out of bounds. Not really sure I understand what is happening here either.

I have a separate driver class that calls the GUI class to run the program. See below.

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);
    }



}
0

1 Answer 1

2

First you will have to create the logic for the multiply button, something like:

  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
        }
    });

then defined the method to multiply recursively:

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);
}

So the idea is you pass the list and a count variable. This count will tell the current position of the list of numbers. For each recursive call you take the current element from the list numbers.get(count) and call again recursively but adding one to the current count i.e., multiple_recursive(numbers, count + 1);. The recursive calls should stop as soon as the current count is the same as the list size, we return 1, because of the multiplicative identity property of that value.

For a list with the element {5, 2, 10}. The iterations will be like:

  1. numbers.size() == count False
  2. return numbers.get(0) * multiple_recursive(numbers, 1);
  3. return 5 * (multiple_recursive(numbers, 1));
  4. return 5 * (numbers.get(1) * multiple_recursive(numbers, 2));
  5. return 5 * (2 * multiple_recursive(numbers, 2));
  6. return 5 * (2 * (numbers.get(2) * multiple_recursive(numbers, 3)));
  7. return 5 * (2 * (10 * multiple_recursive(numbers, 3)));
  8. since numbers.size() == count is True then
  9. return 5 * (2 * (10 * 1));
  10. return 50
Sign up to request clarification or add additional context in comments.

1 Comment

thank you this explanation helped clarify several things for me. I will need to practice this more to get good at it. I appreciate your assistance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.