Sunday 29 May 2011

Calculate Circle Area using Java

  1. /*
  2. Calculate Circle Area using Java Example
  3. This Calculate Circle Area using Java Example shows how to calculate
  4. area of circle using it's radius.
  5. */
  6. import java.io.BufferedReader;
  7. import java.io.IOException;
  8. import java.io.InputStreamReader;
  9. public class CalculateCircleAreaExample {
  10. public static void main(String[] args) {
  11. int radius = 0;
  12. System.out.println("Please enter radius of a circle");
  13. try
  14. {
  15. //get the radius from console
  16. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  17. radius = Integer.parseInt(br.readLine());
  18. }
  19. //if invalid value was entered
  20. catch(NumberFormatException ne)
  21. {
  22. System.out.println("Invalid radius value" + ne);
  23. System.exit(0);
  24. }
  25. catch(IOException ioe)
  26. {
  27. System.out.println("IO Error :" + ioe);
  28. System.exit(0);
  29. }
  30. /*
  31. * Area of a circle is
  32. * pi * r * r
  33. * where r is a radius of a circle.
  34. */
  35. //NOTE : use Math.PI constant to get value of pi
  36. double area = Math.PI * radius * radius;
  37. System.out.println("Area of a circle is " + area);
  38. }
  39. }
  40. /*
  41. Output of Calculate Circle Area using Java Example would be
  42. Please enter radius of a circle
  43. 19
  44. Area of a circle is 1134.1149479459152
  45. */

No comments: