Reputation: 27
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);
}
}
Upvotes: 0
Views: 74
Reputation: 475
You should clearly understand the difference between local and global variables.
Basically, what you're declaring inside the { }
is a local variable. It is only accessible inside that block. So when in function double sum2(int n)
you're trying to access variables s
and res
they are just not known to that function.
Upvotes: 2
Reputation: 218798
Because there is no s
in the sum2
method. It's in the sum1
method. And a variable declared within a given scope only exists within that scope.
So either sum2
needs to create such a variable:
double sum2(int n)
{
double s = 1.0;
double res = 1.0;
double ts = 0.0;
for(int i = 1;i<=n;i++)
{
ts = s/res;
}
return ts;
}
or it needs to accept that variable as a parameter to the method:
double sum2(int n, double s, double res)
{
double ts = 0.0;
for(int i = 1;i<=n;i++)
{
ts = s/res;
}
return ts;
}
(in which case any code which calls sum2()
will need to pass it those values)
Conversely, you can increase the scope. If the entire object should know of s
then make it a class-level variable:
public class SERIES {
double s = 1.0;
// now any method in this class can access the same instance of s
}
Upvotes: 1
Reputation: 26961
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);
}
}
Upvotes: 3