Java test cases - java

import java.text.DecimalFormat;
public class Cylinder
{
// Instance Variables
private String label = "";
private double radius;
private double height;
/**
*#param labelIn Represents label value
*#param radiusIn Represents radius value
*#param heightIn Represents height value
*/
public Cylinder(String labelIn, double radiusIn, double heightIn)
{
label = labelIn.trim();
radius = radiusIn;
height = heightIn;
}
/**
*#return String representation of label.
* Accepts no parameters and returns
* a string representing the label field.
*/
public String getLabel()
{
return label;
}
/**
* Takes string parameter and returns boolean.
*#param labelIn Command Line used
*#return checks to see if labelIn exist.
*/
public boolean setLabel(String labelIn)
{
if (labelIn == null)
{
return false;
}
else
{
label = labelIn.trim();
return true;
}
}
/**
*#return a method to display a double radius.
* Accepts no parameter and returns double representing
* radius.
*/
public double getRadius()
{
return radius;
}
/**
*#param radiusIn Command Line used.
* Accepts a double parameter, sets radius field, and
* returns nothing.
*/
public void setRadius(double radiusIn)
{
radius = radiusIn;
}
/**
*#return a method to display a double height.
* Accepts no parameters and returns double
* representing the height field.
*/
public double getHeight()
{
return height;
}
/**
*#param heightIn Command Line used.
* Accepts a double parameter, sets radius field, and
* returns nothing.
*/
public void setHeight(double heightIn)
{
height = heightIn;
}
/**
*#return displays diameter when method is called.
* Accepts no parameters and returns double value
* for diameter calculated using radius.
*/
public double diameter()
{
return radius * 2;
}
/**
*#return displays circumference when method is called.
* Accepts no parameters and returns double value
* for circumference calculated using Math.PI and radius.
*/
public double circumference()
{
return Math.PI * radius * 2;
}
/**
*#return displays area when method is called.
* Accepts no parameters and returns double value
* for surface area calculated using Math.PI, radius, and height.
*/
public double area()
{
return 2 * Math.PI * radius * radius + 2 * Math.PI * radius * height;
}
/**
*#return displays volume when method is called.
* Accepts no parameters and returns double value
* for volume calculated using Math.PI, radius, and height.
*/
public double volume()
{
return Math.PI * radius * radius * height;
}
/**
*#return displays cylinder information.
* Returns a string containing the information about
* the cylinder object.
*/
public String toString()
{
DecimalFormat fmt = new DecimalFormat("#,##0.0##");
return "\"" + label
+ "\" is a cylinder with radius = " + fmt.format(getRadius())
+ " units and height = " + fmt.format(getHeight()) + " units,"
+ "\nwhich has diameter = " + fmt.format(diameter())
+ " units, circumference = " + fmt.format(circumference())
+ " units,"
+ "\narea = " + fmt.format(area()) + " square units,"
+ " and volume = " + fmt.format(volume()) + " cubic units.";
}
}
I need to write test cases for each method but I'm not really sure how to do that. I tried this..
#Test public void getLabelTest() {
Cylinder c = new String("Cyl");
But I get an incompatible type error. Any help would be appreciated.

Since you are using the #Test annotation, I assume you are supposed to use JUnit testing.
Check here for a short overview how it is done.
You are trying to assign a String to your Cylinder, that's where the incompatible type error comes from. I think you are meant to use
Cylinder c = new Cylinder("Cyl", 1.0, 1.0); // label = "Cyl", radius = 1.0, height = 1.0
Generally you are creating your (JUnit)-Test in a separate java file called a JUnit Test Case and there you are going to create the single tests for your methods annotated with #Test.
Here is simple example how such a JUnit Test Case could look like (related to your setLabel-method):
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class JUnitTest {
private Cylinder c;
#Before
public void setUp() {
// initializing Cylinder instance to work on
c = new Cylinder("Cyl", 1.0, 1.0);
}
#Test
public void setLabelTest() {
// parameter is null, return value should be false
assertFalse(c.setLabel(null));
// parameter is NOT null, return value should be true
assertTrue(c.setLabel("Foo"));
}
}
Also check Assert doc for the different assertions.

Related

Incorrect result for some values when creating a subclass Triangle in Java that computes area and perimeter

I have an assignment that asks me to create a subclass Triangle that extends GeometricObject. I'm very close to getting the solution correct, but there's a problem with my perimeter method. The problem I'm having is that my program is computing the correct perimeter at times and at times computes the perimeter using the initial 1.0 value for all 3 sides.
This is the instructions:
The Triangle Class: Your code folder contains a class named GeometricObject. Without modifying this class in any way, extend it to create a new class named Triangle.
The Triangle class contains:
a single field named sides that consists of an array of three double values, representing side1, side2, and side3. You must use an array; do not use individual instance variables. Each element should have default values of 1.0 to represent the three sides of the triangle.
a no-arg constructor that creates a default Triangle: (new Triangle()).
a constructor that creates a Triangle with the three sides specified: (new Triangle(1.0, 2.0, 1.5)).
a third constructor that takes the three sides, the Color and whether or not the object should be filled: (new Triangle(1.0, 2.0, 1.5, Color.RED, true)).
A method named getArea() that returns the area of the Triangle. (Look up the formula online, using Heron's formula.)
A method named getPerimeter().
A method named toString() that returns a String description of the Triangle.
This is what I've worked on so far (my code):
import java.awt.Color;
public class Triangle extends GeometricObject
{
private double side1 = 1.0;
private double side2 = 1.0;
private double side3 = 1.0;
//no args constructor.
public Triangle ()
{
}
public Triangle (double side1, double side2, double side3)
{
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public double getArea()
{
double s = ( side1 + side2 + side3 ) / 2.0 ;
double area = Math.sqrt ( s * ( s - side1) * (s - side2 ) * (s - side3));
return area;
}
public double getPerimeter()
{
return (side1 + side2 + side3);
}
public Triangle ( double side1 , double side2 , double side3 ,Color color, boolean statement )
{
}
public String toString()
{
return ( "t1.getArea() = " + getArea() + "\nt1.getPerimeter() = " +
getPerimeter() + "\nTriangle: side1 = " +
side1 + ", side2 = " + side2 + ", side3 = " + side3) ;
}
}
This is what I get from checking the Test Program:
Testing Triangle
Class Triangle is defined (0.5)
Class Triangle is public (0.5)
Class Triangle extends GeometricObject (0.5)
Three constructors are defined. (0.5)
Default (no-arg) constructor defined. (1.0)
Triangle(double, double, double) constructor defined. (3.0)
Triangle(double, double, double, Color, boolean) constructor is defined. (1.0)
Correct perimeter for simple triangle. (3.0)
Correct area for simple triangle. (3.0)
Correct perimeter for 3-arg triangle with sides 5.39, 3.56, 8.44 (2.0)
Correct area for 3-arg triangle with sides 10.82, 4.36, 10.47 (2.0)
Correct perimeter for 3-arg triangle with sides 8.41, 7.65, 9.8 (2.0)
Correct area for 3-arg triangle with sides 2.63, 4.51, 1.41 (2.0)
X Incorrect perimeter for 3-arg triangle with sides 6.17, 9.03, 1.64
expected:<16.84> but was:<3.0> (2.0)
X Incorrect perimeter for 3-arg triangle with sides 2.48, 1.86, 2.08
expected:<6.42> but was:<3.0> (2.0)
Correct toString for 3-arg triangle with sides 4.66, 7.65, 1.83 (3.0)--------------------------------------------------------------------------
86% (24.0/28.0 tests passing)
This the code for GeometricObject:
import java.awt.Color;
import java.util.Date;
public class GeometricObject
{
private Color color = Color.WHITE;
private boolean filled;
private Date dateCreated;
/**
* Construct a default geometric object.
*/
public GeometricObject()
{
dateCreated = new Date(); // System time.
}
/**
* Constructs a GeometricObject with a given color and filled state.
* #param color the initial color of the object
* #param filled whether the object is filled
*/
public GeometricObject(Color color, boolean filled)
{
this(); // set the date
this.color = color;
this.filled = filled;
}
/**
* Return current color.
* #return current color.
*/
public Color getColor()
{
return color;
}
/**
* Return true if the object is filled.
* #return true if the object is filled.
*/
public boolean isFilled()
{
return filled;
}
/**
* Set a new filled value.
* #param filled the new filled value.
*/
public void setFilled(boolean filled)
{
this.filled = filled;
}
/**
* Get dateCreated.
* #return the date the object was created.
*/
public Date getDateCreated()
{
return dateCreated;
}
/**
* Return a string representation of this object.
*/
public String toString()
{
return "created on " + dateCreated + "\ncolor: " + color
+ " and filled: " + filled;
}
}
I know this is a long post and I'll would really appreciate your help and thank you in advance for your time and help.

circle class with methods

I am creating a circle class program that checks whether circles have overlapped each other. There are six initial given methods: getter methods for x,y, and radius and setter methods for x,y, and radius(6). There are two additional given methods: getArea method (returns the area's value) and doesOverLap method (returns which circles overlap or do not overlap). There are many demos within this source folder, but the following is the bulk (excuse indentation):
public class MyCircle
{
private double x;
private double y;
private double radius;
private double other_x; //keeps user input for other_x
private double other_y; //keeps user input for other_y
private double other_radius; //keeps user input for other_radius
private double third_x; //keeps user input for third_x
private double third_y; //keeps user input for third_y
private double third_radius; //keeps user input for third_radius
/*
The setX method stores a value in the x field.
# param value The value to store in x.
*/
public void setX(double value)
{
x = value;
}
/*
The setY method stores a value in the y field.
# param value The value to store in y.
*/
public void setY(double value)
{
y = value;
}
/*
The setRadius method stores a value in the radius field.
#param value The value to store in radius.
*/
public void setRadius(double value)
{
radius = value;
}
/*
The getX method returns x's value.
#return The value in the x field.
*/
public double getX()
{
return x; //returns value input for x
}
/*
The getY method return y's value.
#return The value in the y field.
*/
public double getY()
{
return y; //returns value input for y
}
/*
The getRadius method returns radius's value.
#return The value in the radius field.
*/
public double getRadius()
{
return radius; //returns value input for radius
}
/*
The getArea method returns the circle object's area.
#return The product of 3.14159 * radius * radius (area = 3.14159(pie) * radius * radius).
*/
public double getArea()
{
return radius * radius * 3.14159;
}
public boolean doesOverlap(MyCircleTest OtherCircleTest)
{
double distance;
distance = Math.sqrt(Math.pow(other_x - x, 2) + Math.pow(other_y - y, 2));
return distance < other_radius + radius;
if(distance < other_radius + radius)
{
System.out.println("My other circle overlaps my circle");
}
else
{
System.out.println("My other circle does not overlap my circle");
}
}
/*
The setOtherX method stores a value in the x field.
# param value The value to store in x.
*/
public void setOtherX(double value)
{
other_x = value;
}
/*
The setOtherY method stores a value in the y field.
# param value The value to store in y.
*/
public void setOtherY(double value)
{
other_y = value;
}
/*
The setOtherRadius method stores a value in the radius field.
#param value The value to store in radius.
*/
public void setOtherRadius(double value)
{
other_radius = value;
}
/*
The getOtherX method returns x's value.
#return The value in the x field.
*/
public double getOtherX()
{
return other_x; //returns value input for x
}
/*
The getY method return y's value.
#return The value in the y field.
*/
public double getOtherY()
{
return other_y; //returns value input for y
}
/*
The getRadius method returns radius's value.
#return The value in the radius field.
*/
public double getOtherRadius()
{
return other_radius; //returns value input for radius
}
/*
The getArea method returns the circle object's area.
#return The product of 3.14159 * radius * radius (area = 3.14159(pie) * radius * radius).
*/
public double getOtherArea()
{
return other_radius * other_radius * 3.14159;
}
public boolean doesOverlap(MyCircleTest OtherCircleTest)
{
//Equation to see whether circles overlap
double distance_2;
distance_2 = Math.sqrt(Math.pow(other_x - third_x, 2) + Math.pow(other_y - third_y, 2));
return distance < other_radius + third_radius;
if(distance_2 < other_radius + third_radius)
{
System.out.println("My other circle overlaps my third circle");
}
else
{
System.out.println("My other circle does not overlap third circle");
}
}
public void setThirdX(double value)
{
third_x = value;
}
/*
The setThirdY method stores a value in the third y field.
# param value The value to store in third y.
*/
public void setThirdY(double value)
{
third_y = value;
}
/*
The setThirdRadius method stores a value in the third radius field.
#param value The value to store in third radius.
*/
public void setThirdRadius(double value)
{
third_radius = value;
}
/*
The getThirdX method returns third x's value.
#return The value in the third x field.
*/
public double getThirdX()
{
return third_x; //returns value input for third x
}
/*
The getY method return third y's value.
#return The value in the third y field.
*/
public double getThirdY()
{
return third_y; //returns value input for third y
}
/*
The getThirdRadius method returns third radius's value.
#return The value in the third radius field.
*/
public double getThirdRadius()
{
return third_radius; //returns value input for third radius
}
/*
The getArea method returns the circle object's area.
#return The product of 3.14159 * radius * radius (area = 3.14159(pie) * radius * radius).
*/
public double getThirdArea()
{
return third_radius * third_radius * 3.14159;
}
public boolean doesOverlap (MyCircleTest ThirdCircleTest)
{
//Equation to see whether circles overlap
double distance_3;
distance_3 = Math.sqrt(Math.pow(third_x - x, 2) + Math.pow(third_y - y, 2));
return distance_3 < third_radius + radius;
if(distance_3 < third_radius + radius)
{
System.out.println("My third circle overlaps circle");
}
else
{
System.out.println("My third circle does not overlap circle");
}
}
}
I am having trouble on the final method, doesOverLap method, which should state the overall results of the program. It should state whether or not two circles overlap. Also, I am supposed to display the area values of each circle, which isn't in my code.
Requirements are the following:
There are three circle objects, two of them should overlap and two of them should not. The areas of the three circles are to be displayed. The doesOverLap method should indicate which circles over lap and which do not. Any help will be greatly appreciated.
Hinted Given: two circles overlap if the sum of their radius' is greater than the distance between their centers.
First of all, as #JF Meier pointed out in the comments, this is not the OO approach. You should have a class Circle which contains data and logic relevant for only a single circle and then create multiple instances of the Circle class with which you can work.
Also, I don't know if this code template was provided or created by yourself, but the initial data should be passed through a constructor rather than having only setters. Which makes sense, because a circle should be immutable in my opinion.
For example:
public class Circle {
private final double x;
private final double y;
private final double radius;
public Circle(double x, double y, double radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
}
With this, you need only one variant of getArea() and doesOverlap(Circle other) because now each of those methods "belong" to one Circle object alone.
Now you can simply create new instances of multiple circles and use your methods on them.
BTW: If you have parameters in one of your methods like doesOverlap(Circle other) make sure you actually use other inside.

Creating a Cylinder Class

I'm currently undertaking a Java class (one of my final ones for my bachelor, yay) and I'm having a really difficult time trying to understand classes and do this problem below. The textbook I'm currently using is quite confusing and I've tried to use other online resources to figure out what I'm doing wrong but I still seem stuck on the question below. Whenever I try and run the program all I get is 0.00.0 for my answer, is this due to myself incorrectly assigning values to cylinder1? Also, for the toString() class how do I even go about doing this? I'm always getting errors on converting doubles to Strings no matter what I can do.
Any help would be appreciated it.
Thanks.
Prompt
Implement the class called Cylinder shown in UML below. The constructor accepts and initializes the radius and height for the Cylinder, while accessors and mutators allow them to be changed after object construction. The class also include methods that calculate and return the volume and surface area of the Cylinder. Lastly, it contains a toString method that returns the name of the shape, its radius, and its height. Create a main method which instantiates 4 Cylinder objects (any parameters), display them with toString(), change one parameter (your choice) in each, and display them again. [15 points]
UML
Code
import java.util.*;
import java.text.*;
import java.io.*;
import java.lang.*;
class Cylinder
{
private double radius, height, area, volume;
public Cylinder(double height, double radius) {
radius = 0.0;
height = 0.0;
}
public double getRadius() {
return radius;
}
public double getHeight() {
return height;
}
public double getArea() {
double area = (2 * Math.PI * radius * height) + (2 * Math.PI * Math.pow(radius, 2));
return area;
}
public void setRadius(double r) {
radius = r;
}
public void setHeight(double h) {
height = h;
}
public double calcVolume() {
double volume = Math.PI * Math.pow(radius, 2) * height;
return volume;
}
public String toString (){
StringBuilder StBuild = new StringBuilder();
StBuild.append(radius).append(height);
return StBuild.toString();
}
public static void main(String[] args) {
Cylinder cylinder1 = new Cylinder(5, 5);
System.out.println(cylinder1);
}
}
Since this is obviously homework I won't give you the answers, but I'll try to explain a few things.
This:
public Cylinder(double height, double radius) {
radius = 0.0;
height = 0.0;
}
is a constructor. When you create an object (and instance of a class) you call this. You call it by doing:
Cylinder cylinder1 = new Cylinder(5, 5);
But what happens in your class? When you call the constructor are you really saving the values you want?
As for the toString method, you could either call the toString for the double (height.toString) or you could just do what I always end up doing which is just cheat by adding a string to it.
public String toString (){
return "Cylinder [ h: " + height + " - r: " + radius + " - v: " + calcValume() + "]";
}
in class Cylinder change the constructor to:
public Cylinder(double height, double radius) {
this.radius = radius;
this.height = height;
}
In void main() :
Cylinder cylinder1 = new Cylinder(5, 5);
System.out.println(cylinder1.calcVolume());
This will work.
But you should shift the main method to some other class.
In the constructor you are setting the radius and height to 0.0. Try:
public Cylinder(double height, double radius) {
this.radius = radius.
this.height = height;
}

Robot method how to access two different objects in the class

I'm trying to write a simple code that calculates the manhattan distance between two robots. The manhattan distance is simply |x1-x2| + |y1-y2|. I have written most of the code but am not sure how to access the x,y coordinates of the second robot that I have created
/**
* Project 1 -- Robot Position Calculator
*
* This program creates two Robot objects and
* calculates the distance between them.
* #author your name
* #lab section number and lab instructor's name
* #date date of completion
*/
import java.util.Scanner;
/**
* The name of each robot is provided as input from the user.
* The position of each robot is assigned randomly through the constructor.
* The method distance returns the distance between this robot and the other robot.
*/
public class Robot {
/**
* The name of the Robot.
*/
String name;
/**
* The x-coordinate of the Robot location.
*/
double x;
/**
* The y-coordinate of the Robot location.
*/
double y;
/**
* Constructor to assign values for instance variables
* name assigned using the passed argument. Member variables
* x and y are assigned random real values in range [0, 1).
*
* #param name the robot name
*/
public Robot(String name) {
// TODO assign this.name
this.name = name;
// TODO assign this.x and this.y using separate calls to Math.random()
x = Math.random();
y = Math.random();
}
/*
* Returns the robot name.
*
* #returns a string containing no whitespace
*/
public String getName() {
return this.name;
}
/*
* Returns the x-coordinate of the robot location
*
* #returns a real value in range [0, 1)
*/
public double getX() {
return this.x;
}
/*
* Returns the y-coordinate of the robot location
*
* #returns a real value in range [0, 1)
*/
public double getY() {
return this.y;
}
/*
* Calculate the Manhattan distance between the robot's location
* and the location specified by coordinates (x, y), i.e.:
*
* #param xCoord a real value for x-coordinate
* #param yCoord a real value for y-coordinate
* #returns a real value representing the distance
*/
public double distance(double xCoord, double yCoord) {
System.out.println(x);
System.out.println(y);
double distance = Math.abs(x - this.getX()) + Math.abs(y - this.getY());
return distance;
}
/**
* main() Method
* The main method must do the following:
* Input Name for robOne
* Input Name for robTwo
* Create the robOne object
* Create the robTwo object
* Display position of robOne
* Display position of robTwo
* Calculate the distance between both robots by calling distance function
* Display distance between the robots
*
* #param args can be ignored.
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert your name for the first Robot below...");
String a = in.nextLine();
Robot x = new Robot(a);
System.out.println("Insert your name for the second Robot below...");
String b = in.nextLine();
Robot y = new Robot(b);
System.out.println(x.getName() + ": (" + x.getX() + ", " + x.getY() + ")");
System.out.println(y.getName() + ": (" + y.getX() + ", " + y.getY() + ")");
// TODO Call distance(double xCoord, double yCoord) method of robOne
double d = x.distance(y.getX(), y.getY());
// TODO Print out the Manhattan distance between the robots in line 3
System.out.println(d);
// Note: be sure to adhere to the output format described below
}
}
This will fix your problem:
public double distance(final double xCoord, final double yCoord) {
System.out.println(x);
System.out.println(y);
final double distance = Math.abs(x - xCoord) + Math.abs(y - yCoord);
return distance;
}
Before, you were calculating the distance between your own object, and that should be 0 all the time.
Simply do that :
public double distance(Robot other) {
return Math.abs(other.x - this.x) + Math.abs(other.y - this.y);
}
The second robot is passed along when calling the method distance for the first robot like
firstRobot.distance(secondRobot);
Then the x and y coordinates of the second robot are accessible in the method distance as other.x and other.y.
Be also sure to check if the passed robot is really one or null. In case of passing null,
firstRobot.distance(null);
your method will throw a NullPointerException when accessing either other.x or other.y.
Let's look at what you're doing already:
public double distance(double xCoord, double yCoord) {
System.out.println(x);
System.out.println(y);
double distance = Math.abs(x - this.getX()) + Math.abs(y - this.getY());
return distance;
}
The problem with this code is that x and this.getX() are the same value. You are manually accessing your instance variable of x as well as using the getter method that you created to get the same exact value. Because of this, your distance method will always return zero.
What you want to do is compare your current Robot (this) with a different Robot. So, change your method to something like this:
public double distance(Robot other) {
return Math.abs(this.getX() - other.getX()) + Math.abs(this.getY() - other.getY());
}
This way, you are accessing the X and Y instance variables of your current object as well as the object that is passed to your method.

Rectangle Object-Oriented Development - Equals() method

need some help here. Working on "Classes and Object-Oriented Development" and could use some help with both my logic and code for a question in the textbook.
Question: I am asked to Modify my previous example of my Rectangle class to override the equals() and toString() methods. Two rectangles are equal when they both have the same length and width.
My approach: I tried to change it to do this, and then decided it would be easier to compare by areas, rather than comparing both by width and length, so below is what I have so far. Let me know if you have any ideas to help. There is a previous example of the equals() method that compares a circle's radius but isnt helping when comparing 2 different things. Thanks before hand all ! If your wondering why they are all not their own separate files, I haven't gotten there in the chapter yet so it's alot to look at I know ;P
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package chapter8javaExamples;
/**
*
* #author Eric
*/
public class Rectangle {
private double length, width;
/**
* constructor
* pre: none
* post: A rectangle class is created.
*/
public Rectangle() {
length = 2; //default length
width = 4; //default width
}
/**
* constructor
* pre: none
* post: A rectangle object is created with length and width.
*/
public Rectangle (double l, double w) {
length = l;
width = w;
}
/**
* Changes the length of the rectangle
* pre: none
* post: Length has been changed.
*/
public void setLength (double newLength) {
length = newLength;
}
/**
* Changes the width of the rectangle.
* pre: none
* post: Width has been changed.
*/
public void setWidth (double newWidth) {
width = newWidth;
}
/**
* Returns the length of the rectangle.
* pre: none
* post: The length of the rectangle has been returned.
*/
public double getLength() {
return(length);
}
/**
* Returns the width of the rectangle.
* pre: none
* post: The width of the rectangle has been returned.
*/
public double getWidth() {
return(width);
}
/**
* Returns the area of rectangle
* pre: none
* post: The area of the rectangle is returned
*/
public double area() {
double triArea;
triArea = length * width;
return(triArea);
}
/**
* Returns the perimeter of the rectangle
* pre: none
* post: The perimeter of the rectangle is returned
*/
public double perimeter() {
double triPer;
triPer = length + width + length + width;
return(triPer);
}
/**
* Displays the formula for area of a rectangle.
* pre: none
* post: The formula is displayed.
*/
public static void displayAreaFormula(){
System.out.println("The formula for the area of a rectangle is a=l*w");
}
/**
* Determines if the object is equal to another
* Circle object.
* pre: c is a Circle object.
* post: true has been returned if the objects have
* the same radii, false otherwise.
*/
public boolean equals(Object r) {
Rectangle testObj = (Rectangle) r;
Rectangle testObj2 = (Rectangle) r2;
if (testObj.getArea() == area && testObj2.getArea == area()) {
return(true);
} else {
return(false);
}
}
/**
* Returns a String that represents the Circle object.
* pre: none
* post: A string representing the Circle object has
* been returned.
*/
public String toString(){
String rectangleString;
rectangleString = "Rectangle has the Area " + length*width;
return(rectangleString);
}
/**
*
* #param args
*/
public static void main(String [] args){
Rectangle spot = new Rectangle();
Rectangle spot2 = new Rectangle(5, 9);
System.out.println("Area is: " + spot.area());
System.out.println("Perimeter: " + spot.perimeter());
Rectangle.displayAreaFormula();
}
}
I don't think that comparing the areas is a good idea in the equals method, because a rectangle that is 2x8 would equal a rectangle that is 4x4, because both areas are 16. This contradicts your requirement:
Two rectangles are equal when they both have the same length and width.
Here, your r2 variable is undefined. But beyond that, the equals method shouldn't compare two other objects, it should compare this object to another object.
You should return true if the r object is a Rectangle and this rectangle's length matches the other rectangle's length and this rectangle's width matches the other rectangle's width.
Your equals method should always have the following structure:
public boolean equals(Object r) {
if(r == null || !r instanceof Rectangle) return false;
// rest of the code
}
This is because you don't want to perform operations on a null-reference (which would throws errors), and this can't equals null anyway. Secondly: if r is not an instance of the rectangle class, we can quit before having to perform other operations, because a Rectangle would not equal a String, or a Circle.
Now, to get to your question: if you want to check on equality purely by width and length, I would write the method like this:
public boolean equals(Object r) {
if(r == null || !r instanceof Rectangle) return false;
if(length == r.length && width == w.width) return true;
return false;
}
This compares the width and length. If they are both equal, two rectangles are equal. You are comparing the area, but this could give false positives. Take this example:
Rectangle r1;
Rectangle r2;
r1.width = 10;
r1.length = 5;
r2.width = 5;
r2.length = 10;
Your code would produce a positive, while these rectangles are orientated differently.
Two rectangles are equal when they have both same length and width.
Are these following rectangles the same?
and
Hey! Both have the same area don't they?
So in short, no you have use && to see if the length and breadth of both are equal or you could compare the .toString()s of both rectangles to see if they are exact.
To add to the other answers (read those first)
If you are comparing "physical" objects (a block of wood for example) then you might want to compare length to width and width to length as well. The orientation a user inputs might be submitted differently for two of the same objects. Consider this when reading your requirements.

Categories