OOP Example in java | class, method, constructor, getter and setter, access modifiers, throw exception

  • برمجة جافا

Question 1:                                                                                                                                                       

Write a class Rectangle that has the following private attributes/fields:

·       name → (String, should be final)

·       side1 (double)

·       side2 (double)

·       side3 (double)

·       side4 (double)

·       noRectangles (int, should be static. This is a counter of the number of Rectangle objects).

2- Write the full-argument constructor, the no-argument constructor and the copy-constructor.

 

Note 1: the no-argument constructor and the copy-constructor need to call the full-argument constructor. The no-argument constructor sets name to “InternalNameX”, where X is the value of noRectangles, and it sets the sides to 1.0.

Note 2: validate the input in the full-argument constructor such that if the name is null it sets the attribute name to “InternalNameX”, where X is the value of noRectangles, and if the sides are not strictly positive, it sets them to 1.0. It also must check the values of the sides constitute a rectangle (side1 equals sides3 and side2 equals side4). If not, an IllegalArgumentException is generated.   

 

3- Write the getters and setters of all the attributes.

Note 3: validate the input in the setters according to Note 1

 

4- Assuming the values of the sides constitute lengths in meter, overload two methods computeArea and computePerimeter (the return type of both is double) as follows:

·       If they take no argument they compute the area and the perimter in meter.

·       If they take one argument, then they check if the argument is “cm” (case insensitive) they return the area and the perimeter in centimeter, and if the argument is “inch” (case insensitive) they return the area and perimeter in inch. If the argument is none of these values, they throw an IllegalArgumentException.

 

Question 2:                                                                                                                                                      

1- Write a test class named “PractisingClasses” as follows:

·       It prints the following menu to the user:

Please choose one of the following options:

1. Create a default rectange.

2. Create a defined rectangle.

3. Exit.

Enter your choice:  

·       It reads the user input, if the input is 1, it creates a rectangle using the no-argument constructor. If the input is 2, the following form will be given to the user to fill: 

Enter name:

Enter the length of the first side in meters:

Enter the length of the second side in meters:

Enter the length of the third side in meters:

Enter the length of the forth side in meters:

 

When the user enters a name that already exists, or a name that starts with “InternalName”(case insensitive), an error message is dipalyed to him asking him to enter another name. As follows:

Enter name: InternalName66

ERROR: you cannot choose a name that starts with“InternalName”, or a name that already exists, please choose another name:

Enter name: 

Note 5: Create an array and add in it any rectangle object that has been created.

·       When the user choose 3 in the main menu, the program prints the name and the area in meter, centimeter and inch for each rectangle. It also prints the name and the area of the largest rectangle and the smallest rectangle (with respect to the area).

Note 6: Print the decimal numbers in two decimal points format.   

Note 4: to convert from meter to inch multiply by 39.37. 

الأجوبة

Question1: 

public class Rectangle {
    private final String name;
    private double side1;
    private double side2;
    private double side3;
    private double side4;
    private static int noRectangles;

    // full-argument constructor
    public Rectangle(String name, double side1, double side2, double side3, double side4) {
        if (name == null) {
            this.name = "InternalName" + noRectangles;
        } else {
            this.name = name;
        } 
        if (side1 <= 0) {
            this.side1 = 1;
        } else {
            this.side1 = side1;
        }
        if (side2 <= 0) {
            this.side2 = 1;
        } else {
            this.side2 = side2;
        }
        if (side3 <= 0) {
            this.side3 = 1;
        } else {
            this.side3 = side3;
        }
        if (side4 <= 0) {
            this.side4 = 1;
        } else {
            this.side4 = side4;
        }
        if (side1 != side3 || side2 != side4) {
            throw new IllegalArgumentException("Not a rectangle!");
        }
        noRectangles++;
    }
    
    // no-argument constructor
    public Rectangle() {
        this("InternalName" + noRectangles, 1.0, 1.0, 1.0, 1.0);
    }
    
    // copy constructor
    public Rectangle(Rectangle r) {
        this(r.name, r.side1, r.side2, r.side3, r.side4);
    }

    // getters
    public String getName() {
        return name;
    }

    public double getSide1() {
        return side1;
    }

    public double getSide2() {
        return side2;
    }

    public double getSide3() {
        return side3;
    }

    public double getSide4() {
        return side4;
    }

    public static int getNoRectangles() {
        return noRectangles;
    }

    // setters
    public void setSide1(double side1) {
        if (side1 <= 0) {
            this.side1 = 1;
        } else {
            this.side1 = side1;
        }
    }

    public void setSide2(double side2) {
        if (side2 <= 0) {
            this.side2 = 1;
        } else {
            this.side2 = side2;
        }
    }

    public void setSide3(double side3) {
        if (side3 <= 0) {
            this.side3 = 1;
        } else {
            this.side3 = side3;
        }
    }

    public void setSide4(double side4) {
        if (side4 <= 0) {
            this.side4 = 1;
        } else {
            this.side4 = side4;
        }
    }
    
    public double computeArea() {
        return this.side1 * this.side2;
    }
    
    public double computeArea(String unit) {
        
        if (unit.equalsIgnoreCase("cm")) {
            // return this.side1 * this.side2 * 10000;
            return this.computeArea() * 10000;
            
            /*another way:*/
            // return this.computeArea() * Math.pow(100, 2);
            
            /*another way also:*/
            //return (this.side1*100)*(this.side2*100);
        } else if (unit.equalsIgnoreCase("inch")) {
            return this.computeArea() * Math.pow(39.37, 2);
            
            /*another way:*/
            //return (this.side1*39.37)*(this.side2*39.37);
        } else {
            throw new IllegalArgumentException("Invalid unit!");
        }
    }
    
    public double computePerimeter() {
        return (this.side1 + this.side2) * 2;
    }
    
    public double computePerimeter(String unit) {
        
        if (unit.equalsIgnoreCase("cm")) {
            //return this.computePerimeter() * 100;
            
            /*another way:*/
            return ((this.side1*100)+(this.side2*100))*2;
        } else if (unit.equalsIgnoreCase("inch")) {
            //return this.computePerimeter() * 39.37;
            
            /*another way:*/
            return ((this.side1*39.37)+(this.side2*39.37))*2;
        } else {
            throw new IllegalArgumentException("Invalid unit!");
        }
    }
}

 

Question2:

import java.util.Scanner;
import java.text.DecimalFormat; 

public class PractisingClasses {
    
    /**
     * 
     * This method extends the given array by creating another array whose 
     * size is greater than the size of the given array by 1. It copies the 
     * elements of the given array to the new array.
     * 
     * @param recArry an array to extend
     * @return Rectangle[]: the new array.
     */
    public static Rectangle[] extendRecArray(Rectangle[] recArr) {
        
        // Create a new array that has one more space than recArr
        Rectangle[] newRecArr = new Rectangle[recArr.length + 1];
        
        // Copy the elements of recArr to the new Array
        for (int i = 0; i < recArr.length; i++) {
            newRecArr[i] = recArr[i];
        }
        // return the new Array
        return newRecArr;
    }
    
    /**
     * 
     * This method checks if there is a rectangle in the array 'rec' whose name 
     * is 'name'.
     * 
     * @param rec an array rectangles.
     * @param name a name to check if there is any rectangle having its name as it.
     * @return Rectangle[]: the new array.
     */
    public static boolean nameExists(Rectangle[] rec, String name) {
        
        boolean exists = false;
        for (int i=0; i < rec.length && !exists; i++) {
            if (rec[i].getName().equalsIgnoreCase(name)) {
                exists = true;
            }
        }
        return exists;
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner sc = new Scanner(System.in);
        int userIn = 0;
        Rectangle[] recList = new Rectangle[0];
        
        do {
            System.out.println("Please choose one of the following options:");
            System.out.println("\t1. Create a default rectange.");
            System.out.println("\t2. Create a defined rectangle.");
            System.out.println("\t3. Exit.");
            System.out.print("Enter your choice: ");
            
            userIn = sc.nextInt();
            
            switch(userIn) {
                case 1:
                    // extend the array recList by one (check this method above).
                    recList = extendRecArray(recList);
                    recList[recList.length - 1] = new Rectangle();
                    break;
                case 2:
                    String name = null;
                    do {
                        System.out.print("Enter name: ");
                        name = sc.next();
                        if (name.startsWith("InternalName") || 
                                nameExists(recList, name)) {
                            System.out.println("ERROR: Name exists or starts with "
                                    + "\'InternalName\'");
                        }
                    } while (name.startsWith("InternalName") || 
                            nameExists(recList, name));
                    System.out.print("Enter the length of the first side in meters: ");
                    double first = sc.nextDouble();
                    System.out.print("Enter the length of the second side in meters: ");
                    double second = sc.nextDouble();
                    System.out.print("Enter the length of the third side in meters: ");
                    double third = sc.nextDouble();
                    System.out.print("Enter the length of the forth side in meters: ");
                    double fourth = sc.nextDouble();
                    
                    recList = extendRecArray(recList);
                    recList[recList.length - 1] = new Rectangle(name, first,
                    second, third, fourth);
                    break;
                default:
                    if (userIn != 3) {
                        System.out.println("ERROR: unknow input!");
                    }
            }
            
        } while(userIn != 3);
        
        
        double largestArea = Double.MIN_VALUE;
        double smallestArea = Double.MAX_VALUE;
        
        Rectangle largestRec = null;
        Rectangle smallestRec = null;
        
        // to format the decimal numbers in two decimal points.
        DecimalFormat dc = new DecimalFormat("#.##");
        
        for (int i=0; i < recList.length; i++) {
            System.out.println("######################################");
            System.out.println("Name: " + recList[i].getName());
            System.out.println("Area in meter: " + 
                    dc.format(recList[i].computeArea()));
            System.out.println("Area in cm: " + 
                    dc.format(recList[i].computeArea("cm")));
            System.out.println("Area in inch: " + 
                    dc.format(recList[i].computeArea("inch")));
            System.out.println("Perimeter in meter: " + 
                    dc.format(recList[i].computePerimeter()));
            System.out.println("Perimeter in cm: " + 
                    dc.format(recList[i].computePerimeter("cm")));
            System.out.println("Perimeter in inch: " + 
                    dc.format(recList[i].computePerimeter("inch")));
            
            // find the smallest and largest rectangle
            if (recList[i].computeArea() > largestArea) {
                largestArea = recList[i].computeArea();
                largestRec = recList[i];
            }
            if (recList[i].computeArea() < smallestArea) {
                smallestArea = recList[i].computeArea();
                smallestRec = recList[i];
            } 
        }
        
        System.out.println("#############################");
        System.out.println("#############################");
        System.out.println("Largest rec name: " + largestRec.getName());
        System.out.println("Largest rec area: " + 
                dc.format(largestRec.computeArea()));
        
        System.out.println("#############################");
        System.out.println("Smallest rec name: " + smallestRec.getName());
        System.out.println("Smallest rec area: " + 
                dc.format(smallestRec.computeArea()));
        
        // Print the number of Rectangle objects that have been created.
        // Note: Calling a static member does not need creating an object. 
        // You can call it using the class name as below.
        System.out.println("#############################");
        System.out.println("The number of rectangle objects that have "
                + "been created is: " + Rectangle.getNoRectangles());
    }
    
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...