circle class with methods - java

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.

Related

Abstract classes in java not taking any value

I am having a problem with abstract classes, the code runs but it won't take any value , it prints "0.0" everywhere, I'm thinking it is an acces problem.I have to make an abstract base class called "Point" where i declare the 3 coordinates of a point, then i have to calculate the area , volume and center point of a cube and a sphere .Also if something doesn't look good, needs formating, or don't understand a word, please tell me.Thank you.
//this is the base class
public abstract class Punct
{
public double x,y,z;
Punct(double x,double y, double z)
{
this.x=x;
this.y=y;
this.z=z;
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public double getZ()
{
return z;
}
}
Then the sphere
//This is the sphere class that extends the Point class
public class Sfera extends Punct
{
private double aria,volumul,raza,centrul;
Sfera(double x, double y, double z,double aria,double volumul,
double centrul,double raza)
{
super(x, y, z);
this.aria=aria;
this.volumul=volumul;
this.centrul=centrul;
this.raza=raza;
}
public double getRaza(Punct p1,Punct p2)
{
raza=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
return raza;
}
public double getAria()
{
aria=4*Math.PI*raza*raza;
return aria;
}
public double getVolumul()
{
volumul=4/3*Math.PI*raza*raza*raza;
return volumul;
}
public double getCentrul(Punct p1)
{
return centrul;
}
}
The Cube
//this is the cube
public class Cub extends Punct
{
double latura,aria,volumul,centrul;
Cub(double x, double y, double z,double latura, double aria,double volumul, double centrul)
{
super(x, y, z);
this.latura=latura;
this.aria=aria;
this.volumul=volumul;
this.centrul=centrul;
}
public double getLatura(Punct p1,Punct p2)
{
latura=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
return latura;
}
public double getAria()
{
aria=6*Math.pow(latura, 2);
return aria;
}
public double getVolumul()
{
volumul=latura*latura*latura;
return volumul;
}
}
And the Test Class where i have the main
//this is the Test class
public class TestTema
{
public static void main(String[] args_)
{
Punct p1=new Punct(2, 2, 2) {};
Sfera obSfera=new Sfera(1,2,3,1,1,1,1);
System.out.println("Raza sfera:" + obSfera.getRaza(p1,p1));
System.out.println("Aria sfera=" + obSfera.getAria());
System.out.println("Volum sfera= " +obSfera.getVolumul());
// System.out.println("Centrul= "+obSfera.getSuprafata());
Cub obCub=new Cub(1,2,3,1,1,1,1);
System.out.println("Lungime latura cub:"+obCub.getLatura(p1,p1));
System.out.println("Aria cubului="+obCub.getAria());
System.out.println("Volumul cubului="+obCub.getVolumul());
// System.out.println("Suprafata="+obCub.getCentrul());
}
}
Your design is really wrong. Sfera has a method getRaza() that computes the distance between two points. There's no reason to use a Sphere to compute the distance betwwen two points. This should be an instance method of Punct, that should take another point as argument.
But there's worse: instead of just computing the distance between two points, it stores this distance in the Sphere, overwriting its previous raza (not sure why a sphere has a distance):
raza=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
You made the same mistake in several other methods: get methods should not change the state of the object.
Now, let's see your code. You start by calling
obSfera.getRaza(p1,p1)
That computes the distance between p1 and itself, so the answer is 0, and this distance is stored in the Sphere (as explained above). So, after this line of code, you've set the sphere's raza to 0. You then execute
obSfera.getAria()
and this method does
aria=4*Math.PI*raza*raza;
return aria;
so, once again, instead of just returning the area of the sphere, it overwrites its area with the computed value, which is 0 since you've set raza to 0 before.
Here's how a sphere class could look like:
public class Sphere {
private final double radius;
public Sphere(double radius) {
this.radius = radius;
}
public double getArea() {
return 4 * Math.PI * this.radius * this.radius;
}
public double getVolume() {
return (4.0 / 3) * Math.PI * this.radius * this.radius * this.radius;
}
}
Key points:
its fields are final: they can't change.
there is no need to store the volume and the area as fields, since they are derived from the radius
getters don't try to modify the object. They just compute a value and return it.
You are using the same point (p1) to calculate raza, thus replacing the value you used in the constructor. And then you used raza to calculate the other values in the Sfera class.
In the Cub class you are doing the same, so the programm is doing what it is supposed to do. If you calculate those things between the point and itself it will give you 0.
As a result the values you used in your constructor where overwritten by your methods.
System.out.println("Raza sfera:" + obSfera.getRaza(p1,p1));
Sorry, I can't translate what is Raza, but this method calculates distance between two points.
You pass into getRaza the same point. Distance between two identical points is zero. That is why getRaza returns zero.
You assign distance between points to internal field Sfera::raza inthe method getRaza
public double getRaza(Punct p1,Punct p2)
{
raza=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
return raza;
}
So after calling obSfera.getRaza(p1,p1) the field obSfera.raza equals to zero.
All other methods use obSfera.raza in their formulas:
public double getAria()
{
aria=4*Math.PI*raza*raza;
return aria;
}
public double getVolumul()
{
volumul=4/3*Math.PI*raza*raza*raza;
return volumul;
}
Put raza value into your formulas:
volumul = 4/3*Math.PI*raza*raza*raza = 4/3*Math.PI*0*0*0 = 0
aria = 4*Math.PI*raza*raza = aria=4*Math.PI*0*0
The same is happening with the object obCub
create another object for class Punct and rewrite the code like below:
public class TestTema
{
public static void main(String[] args_)
{
Punct p1=new Punct(2, 2, 2) {};
Punct p2=new Punct(3, 3, 3) {};
Sfera obSfera=new Sfera(1,2,3,1,1,1,1);
System.out.println("Raza sfera:" + obSfera.getRaza(p1,p2));
System.out.println("Aria sfera=" + obSfera.getAria());
System.out.println("Volum sfera= " +obSfera.getVolumul());
// System.out.println("Centrul= "+obSfera.getSuprafata());
Cub obCub=new Cub(1,2,3,1,1,1,1);
System.out.println("Lungime latura cub:"+obCub.getLatura(p1,p2));
System.out.println("Aria cubului="+obCub.getAria());
System.out.println("Volumul cubului="+obCub.getVolumul());
// System.out.println("Suprafata="+obCub.getCentrul());
}
}
classes Cub and Sfera both refering the same object p1, so the distance value Math.pow(p2.x-p1.x,2) always be 0.

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.

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.

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.

Inherits in Java

class Box
{
// Instance Variables
double length, ipsos;
double width, mikos;
double height, platos;
// Constructors
public Box ( double side )
{
width = side;
height = side;
length = side;
}
public Box ( double x , double y , double z)
{
platos = y;
ipsos = z;
mikos = x;
}
// Methods
double calculate(double praksi)
{
return 2 * ( width * height +
width * length +
height * length ) ;
}
double volume(double emvadon)
{
return platos * ipsos * mikos;
}
#Override
public String toString() {
return "Volume: " + volume(1) + "\n Calculate: " + calculate(1);
}
}
How can we create a class that inherits MyBox class Box and will be used only for cubes by writing a constructor to ensure the creation of a cube using the second constructor of Box that takes three arguments and in case of an error initializing the cube MyBox to print error message?
I am very new at java, so please explain as simple as possible.
I'm a little confused by why Box has two constructors, and six fields. I would have thought that one constructor and three fields would be enough. But assuming you keep the constructor with three parameters, you can call it from your Cube constructor like this.
The line starting super specifies which Box constructor the Cube constructor should call, and what to pass it. This guarantees that a Cube will always have all three dimensions equal.
public class Cube extends Box {
public Cube(double side) {
super(side, side, side);
}
}

Categories