Calculate Rectangle Perimeter using Java

  1. /*

  2. Calculate Rectangle Perimeter using Java Example

  3. This Calculate Rectangle Perimeter using Java Example shows how to calculate

  4. perimeter of Rectangle using it's length and width.

  5. */

  6.  

  7. import java.io.BufferedReader;

  8. import java.io.IOException;

  9. import java.io.InputStreamReader;

  10.  

  11. public class CalculateRectPerimeter {

  12.  

  13. public static void main(String[] args) {

  14.  

  15. int width = 0;

  16. int length = 0;

  17.  

  18. try

  19. {

  20. //read the length from console

  21. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

  22.  

  23. System.out.println("Please enter length of a rectangle");

  24. length = Integer.parseInt(br.readLine());

  25.  

  26. //read the width from console

  27. System.out.println("Please enter width of a rectangle");

  28. width = Integer.parseInt(br.readLine());

  29.  

  30.  

  31. }

  32. //if invalid value was entered

  33. catch(NumberFormatException ne)

  34. {

  35. System.out.println("Invalid value" + ne);

  36. System.exit(0);

  37. }

  38. catch(IOException ioe)

  39. {

  40. System.out.println("IO Error :" + ioe);

  41. System.exit(0);

  42. }

  43.  

  44. /*

  45. * Perimeter of a rectangle is

  46. * 2 * (length + width)

  47. */

  48.  

  49. int perimeter = 2 * (length + width);

  50.  

  51. System.out.println("Perimeter of a rectangle is " + perimeter);

  52. }

  53.  

  54. }

  55.  

  56. /*

  57. Output of Calculate Rectangle Perimeter using Java Example would be

  58. Please enter length of a rectangle

  59. 10

  60. Please enter width of a rectangle

  61. 15

  62. Perimeter of a rectangle is 50

  63. */

0 comments: