2.5. Studio: Area of a Circle

Get cosy with Java syntax by writing a console program that calculates the area of a circle based on input from the user.

2.5.1. Creating your class

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.

2.5.2. Your first task

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:

  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)

2.5.3. Your next task

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.

    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.

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