Circle functions not behaving as expected in Java Class
Question
so i made a circle class that sets the radius, and should output the radius, circumference and area however, if i input the radius, the radius, circumference, area wont output back, it just shows as 0.0 heres my Circle.java
public class Circle
{
private double radius;
private double PI = 3.14159;
public void setRadius(double rad)
{
radius = rad;
}
public double getRadius()
{
return radius;
}
public double getArea()
{
return PI * radius * radius;
}
public double getDiameter()
{
return 2 * radius;
}
public double getCircumference()
{
return 2 * PI * radius;
}
}
and heres circledemo.java http://pastie.org/466414 -formatting didnt come out well here
First I input the radius, but when i call getRadius, circumference, area, it just outputs 0.0
Solution
Let's walk through the program execution, step by step. First, you initialize some variables and then create a Scanner object. Next, you enter a while
loop. Inside that while loop, you display the main menu, read input from the keyboard, create a new Circle object, and then handle the input you received. And you keep doing that until flag
is set to false
, in which case the program exits.
Notice anything strange here?
A variable only exists inside the scope it was declared in, and your Circle object was declared inside the while loop. Remember, the body of a while loop represents one iteration of a while loop. So, essentially, your Circle object is getting re-created over and over again, which is why setRadius()
is having no effect.
OTHER TIPS
Create the Circle object instance (i.e the code Circle one = new Circle()) OUTSIDE of the while loop. Every iteration of the loop is causing the object to be re-created with new state (i.e. new radius).