2015-12-04 69 views
1

所以我在這裏是新的,這是我的第一個問題......是否有適當的語法在JOptionPane.showMessageDialog中使用for循環?可以在JOptionPane.showMessageDialog中使用for循環嗎?

這是我目前的代碼,我知道它不起作用。我的代碼用於顯示某個整數的因子,我想知道如何在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); 
+0

您不能使用JOptionPane.showMessageDialog這樣,但你可以做你自己的JDialog(其擴展)上與該JTextField(輸入)和一個JLabel(對於結果)和在JTextField上的actionListener(輸入)顯示結果... –

+0

@PetterFriberg謝謝你的直接答案,如果可能的話,你可以提供一個示例代碼?我在開始時忘記提到它,但我仍然是java的初學者。 – Halcyon

回答

0

謝謝皮特FRIBERG給了一個答案,我找到了一個解決方案,我感謝你的問題,雖然我沒有使用您的所有建議。因此,這裏是我的代碼...

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);  
      } 
    } 
} 
相關問題