Online Course Discussion Forum

APCSA chapter 4 question 8

 
 
Picture of Jialin Wang
APCSA chapter 4 question 8
by Jialin Wang - Friday, 24 June 2022, 10:16 PM
 

The screenshots of the code are attatched.

The code works fine if "static" is added to getArea but doesn't work if not and an error message "Cannot make a static reference to the non-static method getArea(int) from the type Circle" pops up.

I think it's because I haven't created an instance of the class getArea, but i'm not sure how to do so with primitive data types, or is the problem something else?

screenshot:https://docs.google.com/document/d/1ttawZ0b68IETxGm0CBpE5wEezf6f0agr/edit?usp=sharing&ouid=108217504462716041350&rtpof=true&sd=true

 
Picture of Dr. Kevin Wang
Re: APCSA chapter 4 question 8
by Dr. Kevin Wang - Saturday, 25 June 2022, 5:17 PM
 

The main() method is static, not part of any instance, and the getArea() method is not static, so it has to be invoked from an instance, like this: circle.getArea(radius). 

There are a few other problems.  The getRadius() method should return "radius", not "r".  The getArea() method, as written, calculates the area of any general circle, not the current instance, so it may be better to use "radius" field to calculate, instead of taking an input argument "r".