// area2: David I. Schwartz 2/1/2000 // find area and perimeter of circle import java.text.DecimalFormat; public class area2 { public static void main(String[] args) { //*************************************************************************** // Set up TokenReader to obtain input: //*************************************************************************** TokenReader in = new TokenReader(System.in); //*************************************************************************** // Choose formula: //*************************************************************************** System.out.print("Enter 1 to compute A. Enter 2 to compute P: "); int choice; choice = in.readInt(); if (choice != 1 && choice != 2) { System.err.println("What the hell was that?"); System.exit(0); } // could we have read input better? See "while" //*************************************************************************** // Declare variables useful for circle formulas: //*************************************************************************** double radius; //*************************************************************************** // Obtain radius: //*************************************************************************** System.out.print("Please enter the radius: "); radius = in.readDouble(); if (radius < 0) { System.err.println("What...are you a loser?"); System.err.println("You must enter a positive radius!"); System.exit(0); } //*************************************************************************** // Report choice to user: //*************************************************************************** System.out.print("\nYou chose to compute "); if(choice == 1) System.out.print("area: " + Math.PI*Math.pow(radius,2) + "\n"); else if(choice == 2) System.out.print("perimeter: " + 2*radius*Math.PI + "\n"); else { System.err.println("Danger! Something is wrong."); System.exit(0); } //*************************************************************************** // Alternative output with formatting: //*************************************************************************** DecimalFormat fmt = new DecimalFormat("0.##"); // 2 decimal places System.out.print("\nYou chose to compute "); if(choice == 1) System.out.print("area (fancy): " + fmt.format(Math.PI*Math.pow(radius,2)) + "\n"); else if(choice == 2) System.out.print("perimeter (fancy): " + fmt.format(2*radius*Math.PI) + "\n"); else { System.err.println("Danger! Something is wrong."); System.exit(0); } } // method main } // class area2