2016-03-07 18 views
0

我需要編寫一個程序來查找數字的因子。如果它是素數,我只需要說它是素數,否則我需要顯示這些因素。我也需要做到這一點,如果它是一個或另一個,它會顯示一個特定的聲明。我可以計算出分解,但如果數字是素數,我不知道如何編寫顯示。這必須使用JOptionPane完成,我非常困惑。使用循環在Java中分解數字

當前代碼:醜陋的

{ 
    String intro = "Hello!\nThis program will ask you to enter a number and will then tell you whether or not it is prime.\n" 
      + "If the number is prime, it will be shown and you will be told it is prime.\n" 
      + "If the number is not prime, it willl be shown followed by it's prime decomposition.\n\n" 
      + "For example, for 41: The number 41 is prime\n" 
      + "For example, for 105: The number 105 will be shown, followed by 3 X 5 X 7"; 
    JOptionPane.showMessageDialog(null, intro, "Prime Decomposer, Introduction",1); 

    String numPrompt = JOptionPane.showInputDialog(null, "Please enter any positive integer.\n" 
        + "The number must be positive, and CANNOT be a decimal value such as 1.5\n\n" 
        + "For example, if you wanted to enter the number 12," 
        + " you would enter: 12", "Prime Decomposer, Integer Entry",1); 
    int userNum = Integer.parseInt(numPrompt); 
    int iteration = 0; 
    int factoredNum = userNum; 
    String decomposition = ""; 
    for(iteration = 2; iteration <= userNum; iteration++) 
     { 
      while(factoredNum % iteration == 0) 
      { 
       decomposition += iteration + " "; 
       factoredNum /= iteration; 
      } 

     } 
     JOptionPane.showMessageDialog(null, "The number "+userNum+" is not prime. Its decomposition is "+decomposition); 
} 
+0

*我非常困惑。* - 你對什麼感到困惑? – shmosel

+0

如果數字是素數,你認爲「分解」會是什麼樣子?你如何測試「分解」的值? – barrowc

+0

@shmosel,我很困惑如何設置另一個JOptionPane,如果它不能被分解成超出自身和1的話,就會說「這個數字是最主要的」。 –

回答

0

類,但我認爲這會工作。

int isPrime = 0;  
for(iteration = 2; iteration <= userNum; iteration++) 
    { 
     while(factoredNum % iteration == 0) 
     { 
      if(iteration<userNum){ 
       isPrime++; 
      } 
      decomposition += iteration + " "; 
      factoredNum /= iteration; 
     } 

    } 
    if(isPrime==0){ 
     JOptionPane.showMessageDialog(null, "The number "+userNum+" is prime. Its decomposition is "+decomposition); 
    }else{ 
     JOptionPane.showMessageDialog(null, "The number "+userNum+" is not prime. Its decomposition is "+decomposition); 
    } 
+0

只有我們沒有涉及的東西布爾人,我不想在演講前冒險使用它。有沒有不同的方式,我可以設置我的while循環,我不必使用布爾值? –

+0

我的意思是一個布爾值只是一個原始數據類型。如果你使用JOptionPanes和'int'和'String',我認爲你沒有問題。給我幾分鐘時間,看看我能否想到另一種方式 –

+0

我編輯了我的代碼,我認爲它會起作用。讓我知道你的想法。 –

相關問題