2016-06-10 54 views
-4

我有一個應該生成任意給定數字n的階乘的程序。使用GUI的Java階乘僅返回第一個輸出

當用戶輸入一個數字時,輸出的數字就是每個輸入到計算器中的數字的階乘。 代碼編譯正常,但計算器不會計算除第一個以外的任何因子。 因爲我不能使用遞歸來解決這個問題,所以請僅使用遞歸發佈答案。

下面的代碼:

import javax.swing.JOptionPane; 

public class Assignment7 
{ 
public static void main(String[] args) 
{ 
int number1; 
int factorial = 1; 
String message; 

number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : ")); 


for(int i = 1; i <= number1; i++) 
{ 
factorial = factorial * i; 


} 



do 
{ 
message = String.format("The factorial of %d is: %d", number1, factorial); 
JOptionPane.showMessageDialog(null, message); 
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : ")); 

} 
while(number1 != 1); 

} 
} 

回答

2

此代碼是可重複的每個輸入

for(int i = 1; i <= number1; i++) 
{ 
    factorial = factorial * i; 
} 

需求。

我建議你的GF把它放到一個可以調用的方法中,該方法將返回結果。

0
import javax.swing.JOptionPane; 

public class Assignment7 
{ 
public static void main(String[] args) 
{ 
int number1; 
int factorial = 1; 
String message; 

number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : ")); 


for(int i = 1; i <= number1; i++) 
{ 
factorial = factorial * i; 


} 



do 
{ 
message = String.format("The factorial of %d is: %d", number1, factorial); 
JOptionPane.showMessageDialog(null, message); 
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : ")); 
factorial = 1; 
for(int i = 1; i <= number1; i++) 
{ 
factorial = factorial * i; 
} 
} 
while(number1 != 1); 

} 
} 
0

您必須重置數字和階乘才能得到正確的階乘。

另外我會考慮使用頭控循環。因爲它更容易理解正在發生的事情。也可以不要把Inputdialog和字符串解析成int爲一行,這使得處理錯誤的用戶輸入變得更容易,你還應該做什麼。 這裏我的解決方案:

import javax.swing.JOptionPane; 

    class Assignment7 { 
     public static void main(String[] args) { 
      int number1 = 0; 
      int factorial = 1; 
      String message; 

      while (number1 != 1) { 
       String positiveInteger = JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "); 
    // You could check if there was a user-input and also later check if it's a number. 
       if (positiveInteger.length() > 0) { 
        number1 = Integer.parseInt(positiveInteger); 
       } 

       for (int i = 1; i <= number1; i++) { 
        factorial = factorial * i; 
       } 

       message = String.format("The factorial of %d is: %d", number1, factorial); 
       JOptionPane.showMessageDialog(null, message); 

       //Reset everything 
       number1 = 0; 
       factorial = 1; 
       message = ""; 
      } 
     } 
    }