About This Solution
This is one way to solve the Circle Calculator assignment. It is not the one and only way.
CircleCalculator.java
package byui.cs246.falin;
// This is sort of like #include in C++, except
// instead of importing the entire library file, it
// just tells the compiler exactly what we mean
// when we type the word "Scanner".
import java.util.Scanner;
public class CircleCalculator {
// By marking this "static final" it acts like a constant.
private static final Scanner _scanner = new Scanner( System.in );
private double getRadius() {
// Using print() instead of println() here, because we don't
// want an end line.
System.out.print("Enter the radius: ");
// Read a double from the console input
double radius = _scanner.nextDouble();
return radius;
}
private void displayArea(double radius) {
// The Java Math class contains many static method and constants
// that are useful for mathematical calculations. See:
// https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
double area = Math.PI * radius * radius;
// Using format specifiers here to control
// the output format. See:
// https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
System.out.format("\tArea: %.2f\n", area);
}
private void displayCircumference(double radius) {
double circ = Math.PI * radius * 2;
System.out.format("\tCircumference: %.2f\n", circ);
}
public static void main(String[] args) {
// In this case, we can't use the alternate syntax we mentioned
// in the HelloWorld solution, because we need to keep a reference to
// the instance in order to call the display methods.
CircleCalculator calc = new CircleCalculator();
double r = calc.getRadius();
calc.displayArea(r);
calc.displayCircumference(r);
}
}