37

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 ");
    }
}
Amir
  • 757
  • 8
  • 15
IvanNewYork
  • 435
  • 2
  • 6
  • 10
  • 10
    The next problem you'll encounter is answered here: http://stackoverflow.com/questions/10455677/division-in-java – Greg Hewgill Sep 26 '12 at 03:14

4 Answers4

54

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);
           ^^      ^
David Yaw
  • 25,725
  • 4
  • 59
  • 90
5

Replace

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

With:

volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;
Daniel Trugman
  • 6,100
  • 14
  • 35
user3394530
  • 51
  • 1
  • 2
  • 7
    Perhaps add some explanation on what you did here? – orhtej2 Oct 20 '17 at 19:25
  • @orhtej2 (4 / 3) returns 1. So he multiplies with 4 a float in order to get a float and then divides with 3, in order to get a float result. – milia Jan 15 '21 at 14:33
4

Here is usage of Math.PI to find circumference of circle and Area First we take Radius as a string in Message Box and convert it into integer

public class circle {

    public static void main(String[] args) {
        // TODO code application logic here

        String rad;

        float radius,area,circum;

       rad = JOptionPane.showInputDialog("Enter the Radius of circle:");

        radius = Integer.parseInt(rad);
        area = (float) (Math.PI*radius*radius);
        circum = (float) (2*Math.PI*radius);

        JOptionPane.showMessageDialog(null, "Area: " + area,"AREA",JOptionPane.INFORMATION_MESSAGE);
        JOptionPane.showMessageDialog(null, "circumference: " + circum, "Circumfernce",JOptionPane.INFORMATION_MESSAGE);
    }

}
Elrond_EGLDer
  • 47,430
  • 25
  • 189
  • 180
tabish ali
  • 41
  • 4
1

Your diameter variable won't work because you're trying to store a String into a variable that will only accept a double. In order for it to work you will need to parse it

Ex:

diameter = Double.parseDouble(JOptionPane.showInputDialog("enter the diameter of a sphere.");
HK boy
  • 1,380
  • 11
  • 16
  • 21
Mark
  • 19
  • 1