Saturday, February 12, 2011

Basic Java Programs


Calculate Circle Area


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

Calculate Circle Perimeter



  1. /*
  2. Calculate Circle Perimeter using Java Example
  3. This Calculate Circle Perimeter using Java Example shows how to calculate
  4. Perimeter 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 CalculateCirclePerimeterExample {
  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. * Perimeter of a circle is
  32. * 2 * pi * r
  33. * where r is a radius of a circle.
  34. */
  35. //NOTE : use Math.PI constant to get value of pi
  36. double perimeter = 2 * Math.PI * radius;
  37. System.out.println("Perimeter of a circle is " + perimeter);
  38. }
  39. }
  40. /*
  41. Output of Calculate Circle Perimeter using Java Example would be
  42. Please enter radius of a circle
  43. 19
  44. Perimeter of a circle is 119.38052083641213
  45. */

No comments:

Post a Comment