Java Cylinders

  • #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);
 

Answers and Replies

  • #2
SteamKing
Staff Emeritus
Science Advisor
Homework Helper
12,796
1,668
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.
 
  • Like
Likes 1 person
  • #3
Borg
Science Advisor
Gold Member
1,885
2,391
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);
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.
 
  • Like
Likes Paul Uszak and friendbobbiny

Related Threads on Java Cylinders

Replies
2
Views
10K
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
4
Views
2K
  • Last Post
Replies
9
Views
2K
  • Last Post
Replies
18
Views
4K
  • Last Post
Replies
9
Views
2K
  • Last Post
Replies
4
Views
998
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
2
Views
3K
  • Last Post
Replies
12
Views
4K
Top