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.

  1. Within the datatypes-studio directory create the following directory structure: src/main/java.
  2. Create a new package named org.launchcode by right-clicking (or ctrl-clicking for some Mac users) on the java directory and selecting New > Package. Be sure to enter org.launchcode as the full name, or your package won’t be created in the correct location.
Note

You may have to right click on the java directory and mark the directory as “Sources root” in order to create a new package.

  1. Create a new class inside the package by right-clicking/ctrl-clicking on the org.launchcode package/folder and selecting New > Java Class.
  2. 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.

Tip

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:

  1. What data type should the radius be?
  2. What is the best way to get user input into a variable 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)

B. The Circle Class

Add a second Java file to your program to delegate the area calculation away from the printing task.

  1. Add a new class in your studios.areaofacircle package called Circle.

  2. 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.

    Tip
    public static Double getArea(Double radius) {
    return 3.14 * radius * radius;
    }
    

  3. 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.

Great work! Don’t forget to save, stage, and commit your work up to GitHub.

Bonus Missions

  1. 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 .

  2. 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.