thenewbie thenewbie - 1 month ago 4
Java Question

Error in using methods in java

I'm still a beginner to using methods in java. I want to print the following series in java using methods.

1 + (1+2)/2! + (1+2+3)/3!.....n terms


I have done this much. I want to know why I'm not able to use
s
in
sum2
method.

public class SERIES {
int factorial(int n) {
int res = 1;
for (int i = 2; i <= n; i++)
res *= i;
return res;
}

int sum1(int n) {
int s = 0;
for (int i = 1; i <= n; i++)
s += i;
return s;
}

double sum2(int n) {
double ts = 0.0;
for (int i = 1; i <= n; i++) {
ts = s / res;
}
return ts;
}

void main(int a) {
int d = sum2(a);
System.out.println(d);
}

}

Answer

declare s and res as class attributes and them will be accessible from ALL methods of your class, also you must change the main and create a double variable, because sum2() method returns a double.

public class SERIES {
    // s and res are accessible in everywhere in SERIES class.
    int s = 0;
    int res = 1;

    int factorial(int n) {
        for (int i = 2; i <= n; i++)
            res *= i;
        return res;
    }

    int sum1(int n) {
        for (int i = 1; i <= n; i++)
            s += i;
        return s;
    }

    double sum2(int n) {
        double ts = 0.0;
        for (int i = 1; i <= n; i++) {
            ts = s / res;
        }
        return ts;
    }

    void main(int a) {
        double d = sum2(a);   // change to double
        System.out.println(d);
    }

}