2016-03-07 17 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

我编辑了我的代码,我认为它会起作用。让我知道你的想法。 –

相关问题