0
try {
    num = Integer.parseInt(userText.getText());
    for (i = 1; i <= num; i++) {
        if (num % i == 0)
            textFieldAns.setText(" "+i);
    }
} catch (Exception e) {
    JOptionPane.showMessageDialog(null, "Please Enter Valid number");
 }

The output doesn't seem to display the factors of the number in a form of a looping statement.

Lukasz Blasiak
  • 642
  • 2
  • 10
  • 16
  • I'm not quite sure what you're asking; you keep setting the text value to `i`. Did you mean to set the text value to its current text value *and* `i`? Or to create a variable to hold the same information and just set the text once? – Dave Newton Apr 26 '21 at 18:10
  • Are you trying to display the elements one by one? If that's the case a `for-loop` isn't going to help you, it will block the EDT until it's finished, if you want to display it one by one you need to use a Swing Timer for this. [For example](https://stackoverflow.com/a/34748083/2180785) – Frakcool Apr 26 '21 at 18:13

1 Answers1

0

You should build the full text in a StringBuilder:

int num = Integer.parseInt(userText.getText());
StringBuilder buf = new StringBuilder();
for (i = 1; i <= num; i++) {
    if (num % i == 0)
        buf.append(" ").append(i);
}
textFieldAns.setText(buf.substring(1));
Andreas
  • 154,647
  • 11
  • 152
  • 247