Search code examples
joptionpane

Can a for loop be used in a JOptionPane.showMessageDialog?


So I'm new here, and this is my first question...Is there a proper syntax for using the for loop in JOptionPane.showMessageDialog?

This is my current code and I know that it doesn't work. My code is for showing the factors of a certain integer and I want to know how can I show that in a JOptionPane.

String c = JOptionPane.showMessageDialog(null
,for(d=1;d<=c;d++){
   if(c%d==0){
     d+" "
   }
 }  
,"The factors of "+c+" are: "
,JOptionPane.INFORMATION_MESSAGE);

Solution

  • Thank you Petter Friberg for giving an answer, I found a solution to my problem thanks to you, although I didn't use all of your suggestions . So here's my code...

    import java.util.*;
    import javax.swing.*;
    public class TestNo3{
        public static void main(String[] args) {
          JTextArea factorsArea = new JTextArea();
          JTextField inputInt1 = new JTextField(5);
          JPanel factorsPanel = new JPanel();
            factorsPanel.add(new JLabel("Enter an integer: "));
            factorsPanel.add(inputInt1);
    
         int int1 = JOptionPane.showConfirmDialog(null, factorsPanel
            ,"Show the factors of a number."
            ,JOptionPane.OK_CANCEL_OPTION);
              if(int1==JOptionPane.OK_OPTION){
                String inputIntS = inputInt1.getText();
                int inputIntI = Integer.parseInt(inputIntS);
    
                for(int numB=1;numB<=inputIntI;numB++){
                  if(inputIntI%numB==0){
                    String outputS = String.format("%5d", numB); 
                    factorsArea.append(outputS);        
                  }
                }
    
                JOptionPane.showMessageDialog(null, factorsArea
                    ,"The factors of "+inputIntI+" are: "
                    ,JOptionPane.INFORMATION_MESSAGE);      
              }
        }
    }