1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Rep Power

    Thumbs up Calculating the area of a circle from the radius.

    Somewhere hidden in this code, you might be able to find the answer to a problem typically set by academics.
    Java Code:
     * This works out the area of a circle as PI * Radius
     * squared. Please carefully look  through the source
     * code to see which bit is doing the mathematics. I
     * don't think this provides perfect answers, but it's
     * close enough.
     * @author Shaun B
     * @version 2012-10-28
    import java.lang.Math;
    import java.util.Scanner;
    public class exerciseOne
        // This is a constant available at a class level
        static final double PI = Math.PI;
        // This will read in our keyboard inputs via the Scanner utility
        static Scanner keyboardInput = new Scanner(System.in);
        // This will tell the main routine to continue running:
        static boolean run = true;
        public static void main(String[] args)
            // Local variables available only in this scope:
            float radius = 0.00f;
            float area = 0.00f;
            int readNumber = 0;
            // Our main loop (will continue until run is set to false):
            while (run)
                System.out.println("Please enter the radius of a circle");
                System.out.println("or enter 0 (zero) to exit this demonstration.");
                // Because we're using the scanner to read in numbers, we
                // need to try it to catch any errors:
                    // Gets a new instance of the keyboard scanner, which takes in
                    // system inputs from the keyboard, and takes the next integer
                    // value
                    readNumber = keyboardInput.nextInt();
                // This will catch an error in case there is a problem with the
                // keyboard entry, ie, it is not an integer number or has
                // illegal characters such as alpha characters:
                catch (Exception e)
                    System.err.println("Illegal keyboard input in main class");
                    run = false;
                    // This will promptly exit the Java run-time environment:
                if(readNumber == 0)
                    run = false;
                    // This answers the criteria on the worksheet in exercise one:
                    radius = readNumber;
                    // Calculates the area of the circle:
                    area = (float) PI * (radius * radius);
                    System.out.print("The area is: ");
                    // Outputs the value as a decimal number:

    Have fun,

    Last edited by Shaun_B; October 30th, 2012 at 01:48 PM. Reason: Needed a bit of editing.

IMN logo majestic logo threadwatch logo seochat tools logo