Robot method how to access two different objects in the class - java

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.

Related

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.

Java test cases

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.

Distance between a Lat/Long & the closest edge of a polygon which is made up of Lat/Longs?

I have a list of Lat/Long coordinates that represents a polygon and a single separate Lat/Long which I know is contained within the polygon.
How do I determine the distance from the single Lat/Long to the closest edge of the polygon? Is there a known Java library for this?
I suggest following solution, which also works in case of a polygon that is around the north pole, where a calculation of the longitude and latitude difference doesn't make sense.
The solution transforms the longitude and latitude of points on the earth into three-dimensional coordinates by using the World Geodetic System 84. With those three-dimensional points, you can calculate the projection of one point on the line defined by two other points in three-dimensional space.
Here is the code doing the calculations. It uses the class javafx.geometry.Point3D, available in Java 8.
/** Semi-major axis of earth in meter */
public static final double WGS84_A = 6378137.0;
/** Semi-minor axis of earth in meter */
public static final double WGS84_B = 6356752.314245;
/** Eccentricity of earth */
public static final double WGS84_E =
Math.sqrt( (WGS84_A * WGS84_A) / (WGS84_B * WGS84_B) - 1);
public static final double DEGREES_TO_RADIANS = Math.PI / 180;
/**
* Calculates a three-dimensional point in the
* World Geodetic System (WGS84) from latitude and longitude.
*/
public static Point3D latLonToPoint3D(double lat, double lon) {
double clat = Math.cos(lat * DEGREES_TO_RADIANS);
double slat = Math.sin(lat * DEGREES_TO_RADIANS);
double clon = Math.cos(lon * DEGREES_TO_RADIANS);
double slon = Math.sin(lon * DEGREES_TO_RADIANS);
double N = WGS84_A / Math.sqrt(1.0 - WGS84_E * WGS84_E * slat * slat);
double x = N * clat * clon;
double y = N * clat * slon;
double z = N * (1.0 - WGS84_E * WGS84_E) * slat;
return new Point3D(x, y, z);
}
/**
* Calculates distance of projection p of vector a on vector b.
*
* Use formula for projection, with p being the projection point:
* <p>
* p = a X b / |b|^2 * b
* </p>
* X being the dot product, * being multiplication of vector and constant
*/
public static Point3D calculateProjection(Point3D a, Point3D b) {
return b.multiply(a.dotProduct(b) / (b.dotProduct(b)));
}
/**
* Calculates shortest distance of vector x and the line defined by
* the vectors a and b.
*/
public static double calculateDistanceToLine(Point3D x, Point3D a, Point3D b) {
Point3D projectionOntoLine =
calculateProjection(x.subtract(a), b.subtract(a)).add(a);
return projectionOntoLine.distance(x);
}
By calling calculateDistanceToLine with the point and the polygon segments' points, you are able to find the nearest line defined by the edge points and extended to infinity. In the case of a concave polygon, this may not be what you want, as you see in the picture.
Taking into account that the distance to the polygon edge must be at least as long as the distance to the nearest edge point, you can get the distance to the edge as:
Math.max(calculateDistanceToLine(x, edgePoint1, edgePoint2),
Math.min(x.distance(edgePoint1), x.distance(edgePoint2)));
Note that this calculation yields also not the distance on the surface of the earth, but the direct distance cutting through the earth. Anyway, it should suffice for choosing the shortest distance.
The function latLonToPoint3Dis a modified version of the function that I found here.
you can just loop through all your edges and calculate the distance between the two points like this:
function double calculateDistance(
double edgeLat1, double edgeLng1,
double edgeLat2, double edgeLng2,
double pointLat, double pointLng) {
//calculate straight/edge
double mS = (edgeLng2 - edgeLng1)/(edgeLat2- edgeLat2);
double tS = edgeLng1 - edgeLng1 * mS;
//calculate helper straight
double mH = -mS;
double tH = pointLng - mH * pointLat;
//calcuate straight intersection
xI = (tH - tS)/(mS - mH);
yI = mH * xI - tH;
//calculate distance
/* in degree
double dInDegree = Math.sqrt((pointLat - xI) * (pointLat - xI)
+ (pointLng - yI) * (pointLng - yI));
return dInDegree;
*/
//in meter
double R = 6371000; // m
double dLat = (pointLat-xI).toRad();
double dLon = (pointLng-yI).toRad();
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(x1.toRad()) * Math.cos(pointLat.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double distanceInMeter = R * c;
return distanceInMeter;
}
I hope this works for you, this is "simple" vector maths.
Check the Single Separate Lat/Long, for the closest coordinate that exists in your list.
Then Gather the two points that are connected to that Coordinate(the one that is closest to your single point) So now you have 4 points.
singlePoint, closestPointToSinglePoint, neighbor1, neighbor2. I'm assuming you have some basic trig experience at this point(no pun intended). What you should do from here is visualize 2 triangles. (singlePoint, closestPointToSinglePoint, neighbor1) and (singlePoint, closestPointToSinglePoint, neighbor2).
At this point, calculate the height of the triangles from the SinglePoint as a reference. You now have 2 distances to the 2 closest edges. Compare, and enjoy your results.

The type of the expression must be an array type but it is resolved to ArrayList<Point2D.Double>

I am trying to figure out the proper way to call arrays from the area method, which are then supposed to calculate the area of the points given. Not sure what the proper way to select the specific x and y coordinates from each array is.
MyPolygon class
import java.util.ArrayList;
import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Double;
/**
* A class that represents a geometric polygon. Methods are provided for adding
* a point to the polygon and for calculating the perimeter and area of the
* polygon.
*/
class MyPolygon {
// list of the points of the polygon
private ArrayList<Point2D.Double> points;
/**
* Constructs a polygon with no points in it.
*/
public MyPolygon() {
points = new ArrayList<Point2D.Double>();
}
/**
* Adds a point to the end of the list of points in the polygon.
*
* #param x
* The x coordinate of the point.
* #param y
* The y coordinate of the point.
*/
public void add(double x, double y) {
points.add(new Point2D.Double(x, y));
}
/**
* Calculates and returns the perimeter of the polygon.
*
* #return 0.0 if < 2 points in polygon, otherwise returns the sum of the
* lengths of the line segments.
*/
public double perimeter() {
if (points.size() < 2) {
return 0.0;
}
int i = 0;
double d = 0;
double total = points.get(0).distance(points.get(points.size() - 1));
while (i < points.size() - 1) {
Point2D.Double point1 = points.get(i);
// double x = point1.x;
// double y = point1.y;
Point2D.Double point2 = points.get(i + 1);
// double x1 = point2.x;
// double y1 = point2.y;
d = point1.distance(point2);
// d = Math.sqrt(Math.pow(x1 - x,2) + Math.pow(y1 - y, 2));
total = total + d;
i++;
}
return total;
}
/**
* Calculates and returns the area of the polygon.
*
* #return 0.0 if < 3 points in the polygon, otherwise returns the area of
* the polygon.
*/
public double area() {
int i = 0;
double a = 0;
double total = 0;
total = total + a;
if (points.size() < 3) {
return 0.0;
}
for (int m = 0; m < points.size(); m++) {
total = total + (points[m].x() * points[m + 1].y()) - (points[m].y() * points[m + 1].x());
}
return 0.5 * total;
}
}
Tester Class
class PolygonTester {
public static void main(String args[]) {
MyPolygon poly = new MyPolygon();
poly.add(1.0,1.0);
poly.add(3.0,1.0);
poly.add(1.0,3.0);
System.out.println(poly.perimeter());
System.out.println(poly.area());
}
}
Your headline is actually already the solution. You use points[m] which is array notation. But points ist not an array. It is a list. Use points.get(int i) instead, as you did in perimeter().
You're going to run out of bounds on the list. Your for loop continues while m < size(). However you access m+1 in your calculation. So if the list contains 5 elements and m = 4, (4 < 5) so keep looping, you will then access m + 1 which is 5. You don't have an index of 5 since these lists are 0 based.
Also the code is probably not compiling because you're using array syntax to access a list. You should say points.get(m)
The solution is quite simple, and is given away by your title (which I assume to be a compiler error.)
You are treating points as an array, which it is not. You access elements of an ArrayList slightly differently: you use points.get(m) instead of points[m]. If you make that change in area, it will work.
ArrayLists are not arrays. They are objects that are indexed with the get(int) method.
Wherever you have points[m], or something similar, replace it with points.get(m). The line would then become:
total = total + (points.get(m).x() * points.get(m + 1).y()) - (points.get(m).y() * points.get(m + 1).x());
That should clear up that issue, but you will still probably get an IndexOutOfBoundsException on the last iteration of the loop, because you will be trying to index m + 1 when m is the last index. You should change your code depending on how you want it to handle the last element.

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