Thread: Help with volume of sphere using a loop. Please & thank you.

1. Member
Join Date
Feb 2013
Posts
33
Rep Power
0

Help with volume of sphere using a loop. Please & thank you.

I just want someone to correct my work and I am not sure if my instructor wants the loop to be in the test file (SphereTest) or in the Sphere file.

The problem below is one of the set of problems I need to do. I just want someone to tell me this is correct because the other problems are similar to this one and I want to know I'm going on the right direction.

Write a function that computes the volume of a sphere.
Use a loop to test your function wherein the
sphere radius ranges from 1 to 100.

Sphere
Java Code:
```class Sphere {
public Sphere() { }

double volume ( int r ) {
double v = 0;
for (int i = 1; i <= r; i++) {
v = (4 * Math.PI * Math.pow(r,3)) / 3;
}
return v;
}

}```
SphereTest
Java Code:
```class SphereTest {
public static void main(String [] args) {

Sphere s = new Sphere();

double v;

v = s.volume(69);

System.out.println();
System.out.println("The radius of the sphere is " + v );
System.out.println();

}
}```

this is a screenshot just in case you have doubts about something

2. Senior Member
Join Date
Oct 2012
Posts
108
Rep Power
0

Re: Help with volume of sphere using a loop. Please & thank you.

I'd email the Professor to clarify, but it makes more sense that the loop would be in the test class, with the output of each call verified correct somehow (even to System.out for manual verification).

3. Member
Join Date
Feb 2013
Posts
33
Rep Power
0

Re: Help with volume of sphere using a loop. Please & thank you.

I tried putting the loop in my test file but I keep on getting errors.
I'm not sure if I'm doing it right.

Sphere
Java Code:
```class Sphere {
public Sphere() { }

double volume ( int r ) {
double v = 0;
v = (4 * Math.PI * Math.pow(r,3)) / 3;
return v;
}
}```
SphereTest
Java Code:
```class SphereTest {
public static void main(String [] args) {

Sphere s = new Sphere();

double v;

v = s.volume();

System.out.println();
for (int i = 1; i <= r; i++) {
System.out.println("With radius of " + i + " the sphere volume is " + v );
}
System.out.println();

}
}```

error:
SphereTest.java:11: error: cannot find symbol
for (int i = 1; i <= r; i++) {

symbol: variable r
location: class SphereTest
2 errors

4. Re: Help with volume of sphere using a loop. Please & thank you.

The error message looks pretty clear to me. It says you're trying to use a variable, r, that doesn't exist in the scope of where you're trying to use it. Solution: don't do this. Only use variables that exist and are available in the scope with which you are trying to use it.

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•