Advertisement
deyanmalinov

02. Class Box + Data Validation

Jun 10th, 2020
903
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1. package DPM;
  2. import java.util.Scanner;
  3. public class Main {
  4.     public static void main(String[] args) {
  5.         Scanner scan = new Scanner(System.in);
  6.         double length = Double.parseDouble(scan.nextLine());
  7.         double width = Double.parseDouble(scan.nextLine());
  8.         double height = Double.parseDouble(scan.nextLine());
  9.         try {
  10.             Box box = new Box(length, width, height);
  11.             System.out.println(String.format("Surface Area - %.2f", box.surfaceArea()));
  12.             System.out.println(String.format("Lateral Surface Area - %.2f", box.lateralSurfaceArea()));
  13.             System.out.println(String.format("Volume - %.2f", box.volume()));
  14.         }catch (IllegalArgumentException exception){
  15.             System.out.println(exception.getMessage());
  16.         }
  17.     }
  18. }
  19. ------------------------------------------------------------------------
  20. package DPM;
  21. public class Box {
  22.     private double length;
  23.     private double width;
  24.     private double height;
  25.     public Box(double length, double width, double height){
  26.         this.setLength(length);
  27.         this.setWidth(width);
  28.         this.setHeight(height);
  29.     }
  30.     public void setLength(double length) {
  31.         if (length <= 0){
  32.             throw new IllegalArgumentException("Length cannot be zero or negative.");
  33.         }
  34.         this.length = length;
  35.     }
  36.     public void setWidth(double width) {
  37.         if (width <= 0){
  38.             throw new IllegalArgumentException("Width cannot be zero or negative.");
  39.         }
  40.         this.width = width;
  41.     }
  42.     public void setHeight(double height) {
  43.         if (height <= 0){
  44.             throw new IllegalArgumentException("Height cannot be zero or negative.");
  45.         }
  46.         this.height = height;
  47.     }
  48.     public double surfaceArea(){
  49.         return (2 * this.length * this.width) + this.lateralSurfaceArea();
  50.     }
  51.     public double lateralSurfaceArea(){
  52.         return (2 * this.length * this.height) + (2 * this.width * this.height);
  53.     }
  54.     public double volume (){
  55.         return this.length * this.width * this.height;
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement