Home > database >  For loop displaying 3 6 9 instead of 1 2 3
For loop displaying 3 6 9 instead of 1 2 3

Time:01-15

I was trying to code a simple for loop program.

The user enters a number (for example 4) and the program will display "Trading day 1/2/3/4" every time the user clicks the "next day" button.

But my for loop is displaying 3 6 9 12 instead and I don't know where I'm going wrong.

The program gets value that the user entered in the input box and changes it to int.

public class startButtonListener implements ActionListener {

    public void actionPerformed(java.awt.event.ActionEvent event) {
        tradingDaysValue = Integer.parseInt(tradingDaysField.getText());
    }

This is the code under another button listener after the program gets the value from the previous button listener.

public class tradeButtonListener implements ActionListener {

    public void actionPerformed(java.awt.event.ActionEvent event) {
        for (int i = 0; i < tradingDaysValue; i  ) {
            tradingDayCounter  ;
            tradingDayLabel.setText("TRADING DAY "   tradingDayCounter);
        }
    }
}

I'm unsure why it's displaying 3 6 9 instead of 1 2 3.

CodePudding user response:

The actionPerformed for tradeButtonListener is executing every time the button is pressed, and this function contains the whole loop. Therefore, the loop gets executed each time you press the button. For example, if your number is 4, four iterations will run each time you press the next day button (effectively increasing the counter four times and setting the text four times), netting you increments of 4: 4,8,12,16.

For what you want, you should only do a for the tradingDayCounter each time you click the tradeButton, which only happens in the counter is < than the tradingDaysValue.

public void actionPerformed(java.awt.event.ActionEvent event) {
  if (tradingDayCounter < tradingDaysValue) {
    tradingDayCounter  ;
    tradingDayLabel.setText("TRADING DAY "   tradingDayCounter);
  }
}
  • Related