我需要编写一个程序来查找数字的因子。如果它是素数,我只需说它是素数,否则我需要显示因素。我也需要这样做,如果它是一个或另一个,它将显示一定的声明。我可以弄清楚分解,但如果数字为素数,我无法弄清楚如何写显示。这必须使用JOptionPane完成,我非常困惑。
当前代码:
{
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 :(得分: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);
}