In: Computer Science
Design a LandTract class that has two fields (i.e. instance variables): one for the tract’s length(a double), and one for the width (a double). The class should have:
a constructor that accepts arguments for the two fields
a method that returns the tract’s area(i.e. length * width)
an equals method that accepts a LandTract object as an argument. If the argument object
holds the same data (i.e. length and width) as the calling object, this method should return
true. Otherwise, it should return false.
a toString method (that returns a String representation of the tract’s length, width, and
area).
Demonstrate the class in a program by creating an array of three LandTract objects initialized with user input. Then, print the info of the LandTract objects stored in the array by invoking the toString method (implicitly or explicity). Also, use the equals method to compare at least two LandTract objects and print wether they are of equal size or not.
Sample Output:
Enter the length of Tract 1: 2
Enter the length of Tract 1: 3
Enter the length of Tract 2: 2
Enter the length of Tract 2: 3
Enter the length of Tract 3: 4
Enter the length of Tract 3: 5
Info of LandTract 1:
Length = 2.0
Width = 3.0
Area = 6.0
Info of LandTract 2:
Length = 2.0
Width = 3.0
Area = 6.0
Info of LandTract 3:
Length = 4.0
Width = 5.0
Area = 20.0
The first and second tracts are the same size.
Find below the code for above case
// LandTract class that has two fields (i.e. instance variables)
LandTract.java
public class LandTract {
double length;
double width;
public LandTract(double length, double width) { // constructor that accepts arguments for the two fields
this.length = length;
this.width = width;
}
public double getArea() {
return (this.length * this.width); // method that returns the tract’s area(i.e. length * width)
}
public boolean equals(LandTract obj) { // equals method that accepts a LandTract object as an argument
if(this.length == obj.length && this.width == obj.width)
return true;
else
return false;
}
public String toString() { // toString method
return "Length = "+this.length+"\nWidth = "+this.width+"\nArea = "+getArea()+"\n";
}
}
Test82.java
import java.util.*;
class Test82 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
LandTract objs[] = new LandTract[3]; // an array of three LandTract objects initialized with user input
double l, w;
for(int i = 0; i < 3; i++) {
System.out.print("Enter the length of Tract "+(i+1)+": ");
l = sc.nextDouble();
System.out.print("Enter the width of Tract "+(i+1)+": ");
w = sc.nextDouble();
objs[i] = new LandTract(l, w);
System.out.println();
}
System.out.println();
for(int i = 0; i < 3; i++) {
System.out.println("Info of LandTract "+(i+1)+":");
System.out.println(objs[i]);
}
System.out.println();
if(objs[0].equals(objs[1])) {
System.out.println("The first and second tracts are the same size.");
} else {
System.out.println("The first and second tracts are not of the same size.");
}
}
}