how to use math.pi in java

IvanNewYork picture IvanNewYork · Sep 26, 2012 · Viewed 494.1k times · Source

I am having problems converting this formula V = 4/3 π r^3. I used Math.PI and Math.pow, but I get this error:

';' expected

Also, the diameter variable doesn't work. Is there an error there?

import java.util.Scanner;

import javax.swing.JOptionPane;

public class NumericTypes    
{
    public static void main (String [] args)
    {
        double radius;
        double volume;
        double diameter;

        diameter = JOptionPane.showInputDialog("enter the diameter of a sphere.");

        radius = diameter / 2;

        volume = (4 / 3) Math.PI * Math.pow(radius, 3);

        JOptionPane.showMessageDialog("The radius for the sphere is "+ radius
+ "and the volume of the sphere is ");
    }
}

Answer

David Yaw picture David Yaw · Sep 26, 2012

You're missing the multiplication operator. Also, you want to do 4/3 in floating point, not integer math.

volume = (4.0 / 3) * Math.PI * Math.pow(radius, 3);
           ^^      ^