Reputation: 225
I have tried many different calculations for trying to get my sphere volume method to work.
My Sphere class is extended from Circle, to get the area from circle, as well as implements my Shape3D interface which allows me to use my volume method.
However, I have tried all of these different formulas for my method and nothing gives me back an accurate volume of a sphere. It is always drastically off.
The one that gets the closest is (4*22*radius * radius * radius )/(3*7); but it is still off.
//return (4/3) * super.area() * radius;
//return (Double)((4*22*getRadius()*getRadius()*getRadius() )/(3*7));
//return (4*22*radius * radius * radius )/(3*7);
//return ( (4/3) * (Math.pow(getRadius(), 3) ) / (Math.PI) );
//return (getRadius() * getRadius() * getRadius() ) * (Math.PI) * (4/3);
//return ( super.area() * getRadius() ) * (4/3);
I am going to attach my code for my Shape abstract class, my Circle class, and my Sphere class, as well as my Shape3D interface.
Maybe I have overlooked something obvious. When I set the radius though and get it the radius returns back normal. So I am not sure why every one of these if completely off.
public class Main {
public static void main(String[] args) {
System.out.println(volume());
}
public static double volume() {
double vol;
double x = 4/3;
double y = Math.pow(30.0, 3);
double z = Math.PI;
vol = y * z * x;
return vol;
//return (4/3) * super.area() * radius;
//return (Double)((4*22*getRadius()*getRadius()*getRadius() )/(3*7));
//return (4*22*radius * radius * radius )/(3*7);
//return ( (4/3) * (Math.pow(getRadius(), 3) ) / (Math.PI) );
//return (getRadius() * getRadius() * getRadius() ) * (Math.PI) * (4/3);
//return ( super.area() * getRadius() ) * (4/3);
}// end sphere volume
}
Upvotes: 0
Views: 2337
Reputation: 22420
Here is a simple java test program for calculating the volume of a sphere that you can use as reference for what you are doing wrong which is that 4/3
returns an int, 1 rather than a double representation of and therefore messes up your calculation:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// notice the descriptive variable names rather than x, y and z
double radius;
double diameter;
double volume;
System.out.print("Enter the radius of the sphere:");
radius = scanner.nextDouble();
diameter = (radius * 2.0);
volume = (4.0 / 3.0) * Math.PI * Math.pow(radius, 3); // instead of 4/3 in yours
System.out.println("The volume is: " + String.format("%.1f", volume));
}
}
Example Usage:
Enter the radius of the sphere: 5
The volume is: 523.6
To confirm it is working correctly you can use Google's sphere volume calculator and confirm it gives the same value:
Upvotes: 1
Reputation: 3300
Instead of
double x = 4/3;
Try
double x = 4.0/3.0;
or
double x = 4.0/3;
or
double x = 4/3.0;
Upvotes: 1