0

I want to calculate the factorial of a number with a get method (I must solve a bigger problem). Here's what I tried and it returns 1:

public Sigma() {
    n = -1;
}

public Sigma(int n) {
    n = n;
}

private int Facto(int n) {
    for (int i = 1; i <= n; i++) {
        result = result * i;
    }
    return result;
}

public int getFacto() {
    return Facto(n);
}
bcsb1001
  • 2,834
  • 3
  • 24
  • 35

2 Answers2

0

The problem is that, in your constructor, you type n = n rather than this.n = n. The problem with this is that the local variable inside the constructor is assigned, rather than your class's field. this.n refers to the field n and is what you want.

You are receiving an output of 1 because the default value of all primitive number fields is 0. Using your code, 0! = 1 (which is correct), so that's your output no matter what you pass into the constructor, as the constructor ignores its parameter.

On an unrelated note, please use camelCase rather than UpperCase for method names (and field names). UpperCase should only be used for classes/interfaces/enums/annotations. Also, result = result * n may be simplified to the (almost) equivalent statement result *= n.

Community
  • 1
  • 1
bcsb1001
  • 2,834
  • 3
  • 24
  • 35
0

For the factorial you need to initialize result in the facto function, like this

private int Facto(int n)
 {
    int result = 1;
    for (int i = 1; i <= n; i++) 
    {
           result = result * i;
    }

    return result;
 }
roka
  • 18
  • 4
  • I am pretty sure (although the question needs to clarify this) that either this assignment occurs but is not shown or `result` is a field assigned to `1`, as there is no compilation error mentioned about an unexpected token (`result`). The real problem lies with the constructor (see my answer). – bcsb1001 Mar 05 '16 at 15:34