2016-06-14 58 views
-1

嘿所以我需要計算一個數字的係數,我插入到我的第一個文本區域,但是當我點擊按鈕時,它給了我0。有人可以幫助PLZ嗎?不勝感激。我也沒有在Java中,所以如果你看到的東西,以提高PLZ份額:)java計算插入數字的能力

FIX向下跌破

+1

你永遠不會調用'faculteit'和'fac'沒有初始化,所以它會保持0,即使你調用該方法。 – Eran

+4

「教師」是指「階乘」嗎? – khelwood

回答

0

必須使用教師法first.Try這個初始化變量FAC:

public void actionPerformed(ActionEvent e) { 
    int temp = Integer.parseInt(textFiled1.getText());//keep in mind that if the text is not a number this will give you an error 
    fac = faculty(temp); 
    textField2.setText("" + fac); 
} 

你也必須修改教師法:

TextField textField1, textField2; 
Button btn; 
static int fac; 
public static int faculteit(int n) { 
    int temp = 1;//this is a temporal variable that we use to compute the output of this method 
    for (int i = 1; i <= n; i++) 
    { 
     temp*= i; 
    } 
    return temp; 
} 
+0

仍然給0:/ – Viktor

+0

@Viktor這段代碼應該可以工作,也許你有一些其他的代碼部分你想告訴我們? – theVoid

+0

@Viktor在'faculteit'方法內使'fac'成爲一個局部變量並將其初始化爲1(即在該方法的開頭添加'int fac = 1;') – Eran

0

請初始化變量FAC爲1 你用0乘以數字和它返回結果爲0。

內faculteit方法和之前的循環,

fac = 1;