Studio: Area of a Circle
Get cozy with Java syntax by writing a console program that calculates the area of a circle based on input from the user.
Creating your class
Since you’re still new to Java and IntelliJ, we’ll provide some extra direction for the first studio.
- Within the
datatypes-studio
directory create the following directory structure:src/main/java
. - Create a new package named
org.launchcode
by right-clicking (or ctrl-clicking for some Mac users) on thejava
directory and selecting New > Package. Be sure to enterorg.launchcode
as the full name, or your package won’t be created in the correct location.
You may have to right click on the java
directory and mark the directory as “Sources root” in order to create a new package.
- Create a new class inside the package by right-clicking/ctrl-clicking on the
org.launchcode
package/folder and selecting New > Java Class. - Name the class
Area
. Select the option to add the file to Git when the window appears.
A. The Area
Class
Write a class, Area
, that prompts the user for the radius of a circle and then calculate its area and print the result.
Recall that the area of a circle is A = pi * r * r where pi is 3.14 and r is the radius.
Unlike some other languages, Java does not have an exponent operator.
Here’s an example of how your program should work:
Enter a radius:
2.5
The area of a circle of radius 2.5 is: 19.625
Some questions to ask yourself:
- What data type should the radius be?
- What is the best way to get user input into a variable
radius
of that type?
Be sure to create a main method to place your code within. It’s signature must be:
public static void main(String[] args)
B. The Circle
Class
Add a second Java file to your program to delegate the area calculation away from the printing task.
Add a new class in your
studios.areaofacircle
package calledCircle
.Create a method called
getArea
inside ofCircle
that takes aDouble
radius
as its only parameter and returns anotherDouble
, the result of the area calculation.Tippublic static Double getArea(Double radius) { return 3.14 * radius * radius; }
Back in
Area
, replace your area calculation line with a call toCircle
.getArea()
.TipCheck out the HelloMethods and Message example from Static Methods for a reference on how to use a class from another file.
Great work! Don’t forget to save, stage
, and commit
your work up to GitHub.
Bonus Missions
Add validation to your program. If the user enters a negative number? a non-numeric character? the empty string? Print an error message and quit. You’ll need to peek ahead to learn about conditional syntax in Java .
Extend your program further by using a while or do-while loop , so that when the user enters a negative number they are re-prompted.