我需要編寫一個程序來查找數字的因子。如果它是素數,我只需要說它是素數,否則我需要顯示這些因素。我也需要做到這一點,如果它是一個或另一個,它會顯示一個特定的聲明。我可以計算出分解,但如果數字是素數,我不知道如何編寫顯示。這必須使用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);
}
*我非常困惑。* - 你對什麼感到困惑? – shmosel
如果數字是素數,你認爲「分解」會是什麼樣子?你如何測試「分解」的值? – barrowc
@shmosel,我很困惑如何設置另一個JOptionPane,如果它不能被分解成超出自身和1的話,就會說「這個數字是最主要的」。 –