-1

I am doing an assignment for my first JAVA programming. So far it has been going well but I am stuck at the last part with using math functions.

double radius;
double diameter;
double volume;

System.out.print("Enter a diameter of a sphere: ");
diameter = keyboard.nextDouble();
radius = diameter / 2;
volume = (4 / 3) * Math.PI * Math.pow(radius, 3.0);
System.out.print("Volume of the sphere is " + volume + ".");

I am trying to use the formula for finding a volume of a sphere using diameter input variable. But I keep getting just the PI as an output.

This is what I am supposed to do.

  1. Add a line that prompts the user to enter the diameter of a sphere.
  2. Read in and store the number into a variable called diameter (you will need to declare any variables that you use).
  3. The diameter is twice as long as the radius, so calculate and store the radius in an appropriately named variable.
  4. The formula for the volume of a sphere is V = 4/3 * PI * radius^3 Convert the formula to Java and add a line which calculates and stores the value of volume in an appropriately named variable. Use Math.PI for PI and Math.pow to cube the radius.
  5. Print your results to the screen with an appropriate message.

What am I doing wrong ? Also how do I make it so the volume displays with E notation?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
James
  • 47
  • 3
  • 8
  • 3
    `(4 / 3)` evaluates to **zero** since Java will be using `Integer Arithmetic`. – PM 77-1 Sep 30 '14 at 01:27
  • Use this formula for the volume instead of yours `4 * Math.PI * Math.pow(radius, 3.0) / 3` (refer to @PM77-1 to see why it is necessary). – Dici Sep 30 '14 at 01:30
  • @PM77-1 You should post a more detailed answer for him to understand – Dici Sep 30 '14 at 01:31
  • See [Division in Java always results in zero (0)?](http://stackoverflow.com/questions/10455677/division-in-java-always-results-in-zero-0). – PM 77-1 Sep 30 '14 at 01:34
  • I see that numerator requires it to be decimal. Is it necessary for every time I use fraction in java? – James Sep 30 '14 at 01:37

1 Answers1

1

I think you might be getting an incorrect ans because of 4/3 in Integer Math give 1 and not 1.33 Try changing you code to what is give below. I tried and worked fine for me.

radius = diameter / 2.0d;
volume = (4.0d / 3.0d) * Math.PI * Math.pow(radius, 3); 
StackFlowed
  • 6,664
  • 1
  • 29
  • 45
T.Woody
  • 1,142
  • 2
  • 11
  • 25