1

I'm decently new to Java. I want the user to be able to input 4 different inputs separately by clicking submit. I'm using a for loop to count, but I do not know how to have the user input their answer multiple times. The for loops just repeats all at once. I'm using arrays to hold the user's answers. Here is part of my code. If you have questions or need more explanation I will def. explain more

private void Question1()
{
    int count = 1;
            QuestionsPanel.add(new JLabel(Q1.getQuestion()));
    QuestionsPanel.add(new JLabel(Arrays.toString(mans1)));

    AnswerField = new JTextField(10);
    AnswerPanel.add(AnswerField);

    Submit = new JButton("Submit");
    AnswerPanel.add(Submit);
    Submit.addActionListener(this);

}

public void actionPerformed(ActionEvent e)
{
    if ((e.getSource() == Submit) && count == 0)

    {
        int value = Integer.parseInt(AnswerField.getText());

        for (int i = 0; i < 4; i++)
        {

            if (value == -1) break;
            ans[i] = value - 1;
            AnswerField.setText("");


        }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mike
  • 53
  • 1
  • 9
  • May you please explain a bit more further, as to why a loop is required, Why a normal counter, can not do this task ? Just when that `counter == 4`, you can disable your `JTextField` for further input. – nIcE cOw Apr 18 '12 at 04:48

1 Answers1

2

This doesn't work because you placed the loop in the ActionListener, which is executed once on button click.

What you should do is to keep a counter of the current answer somewhere

int count = 0;

public void actionPerformed(ActionEvent e) {
  if ((e.getSource() == Submit) && count < 4) {
    int value = Integer.parseInt(AnswerField.getText());

    if (value == -1) break;
    ans[count++] = value - 1;
    AnswerField.setText("")
  }
}

In this way the loop is implicitly managed by the actionlistener: everytime you press submit count is incremented by 1 and the correct answer is placed inside the array. Of course you should do something, like disabling the submit button, upon submitting the fourth answer.

Jack
  • 131,802
  • 30
  • 241
  • 343