Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java Cylinders

  1. Aug 3, 2014 #1
    Why is this java code wrong? I'm unsure why java won't recognize radius and height. Both should be fields for any object of the Cylinder class. My declaration for PI may be off, but that doesn't produce an error.






    public class Cylinder {
    public static final double PI;

    public Cylinder (double a, double b)
    { double radius = a;
    double height = b;}

    double area = radius * radius * PI;
    double volume = PI * radius * radius * height;

    public static void main(String[]args)
    {Cylinder sample1 = new Cylinder (43.0,47.0);
    System.out.println("sample1 area is" + sample1.area);
    System.out.println("Sample1 volume is" + sample1.volume);
     
  2. jcsd
  3. Aug 3, 2014 #2

    SteamKing

    User Avatar
    Staff Emeritus
    Science Advisor
    Homework Helper

    Optimization tip: You've already calculated the area of the base and stored it in the variable 'area'. Why calculate the area again when you calculate the volume of the cylinder? The volume is area * height.
     
  4. Aug 3, 2014 #3

    Borg

    User Avatar
    Science Advisor
    Gold Member

    You are declaring radius and height in the constructor and trying to access them outside of it at the class level when you create the area and volume variables. You can't do that.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Java Cylinders
  1. Java Math.abs() (Replies: 3)

  2. Java Resources (Replies: 4)

  3. [Java] PNGException (Replies: 2)

  4. JAVA GridLayout (Replies: 1)

  5. Java interpreter (Replies: 8)

Loading...