Get cosy with Java syntax by writing a console program that calculates the area of a circle based on input from the user.
Since you’re still new to Java and IntelliJ, we’ll provide some extra direction the first few coding exercises.
First, make a new folder, or package, to hold your studio exercises. Create a
new package named org.launchcode.java.studios.areaofacircle
by
right-clicking (or ctrl-clicking for some Mac users) on the src
directory
in java-web-dev-exercises
and selecting New > Package. Be sure to enter
the full name, or your package won’t be created in the correct location.
Create your class in the java-web-dev-exercises
project within the
package org.launchcode.java.studios.areaofacircle
by
right-clicking/ctrl-clicking on the studios.areaofacircle
package/folder
and selecting New > Java Class. Enter the name Area
. Select the option
to add the file to Git when the window appears.
Write a class, Area
, that prompts the user for the radius of a circle and
then calculate its area and print the result.
Tip
Recall that the area of a circle is A = pi * r * r
where pi
is
3.14 and r
is the radius.
Note
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:
radius
of
that type?Warning
Be sure to create a main
method to place your code within. It’s
signature must be:
public static void main(String[] args)
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 called Circle
.
Create a method called getArea
inside of Circle
that takes a Double
radius
as its only parameter and returns another Double
, the result of
the area calculation.
public static Double getArea(Double radius) {
return 3.14 * radius * radius;
}
Back in Area
, replace your area calculation line with a call to
Circle.getArea()
.
Tip
Check out the HelloMethods
and Message
example from
Static Methods for a reference on how to use a class from another
file.