I have been assigned the following task for an introductory java course:
You should write a class that represents a circle object and includes the following:
Private class variables that store the radius and centre coordinates of the object.
Constructors to create circle objects with nothing supplied, with just a radius value supplied and with a radius and centre coordinates supplied.
Public instance methods that allow the radius and centre coordinates to be set and retrieved (often known as set/get methods).
Public instance methods that return the circumference and area of the circle.
A public class method that tests if two circle objects overlap or not
Here is my code:
import java.lang.Math;
public class Circle {
private double xCentre, yCentre, Radius;
// constructors
public Circle() {
xCentre = 0.0;
yCentre = 0.0;
Radius = 1.0;
}
public Circle(double R) {
xCentre = 0.0;
yCentre = 0.0;
Radius = R;
}
public Circle(double x, double y, double R) {
xCentre = x;
yCentre = y;
Radius = R;
}
//getters
public double getX() {
return xCentre;
}
public double getY() {
return yCentre;
}
public double getRadius() {
return Radius;
}
//setters
public void setX(double NewX) {
xCentre = NewX;
}
public void setY(double NewY) {
yCentre = NewY;
}
public void setRadius(double NewR) {
Radius = NewR;
}
//calculate circumference and area
public double Circumference() {
return 2*Math.PI*Radius;
}
public double Area() {
return Math.PI*Radius*Radius;
}
//determine overlap
public static double Overlap(Circle c1, Circle c2) {
double xDelta = c1.getX() - c2.getX();
double yDelta = c1.getY() - c2.getY();
double separation = Math.sqrt(xDelta*xDelta + yDelta*yDelta);
double radii = c1.getRadius() + c2.getRadius();
return separation - radii;
}
}
}
and
import java.io.Console;
public class cp6 {
public static void main(String args[]){
//Set up the Console
Console myConsole = System.console();
//Declare cirlce
Circle first = new Circle(2.0,4.0,6.0);
myConsole.printf("Circumference of first circle is ", first.Circumference(), "\n");
myConsole.printf("Area of first circle is ", first.Circumference(), "/n");
first.setRadius(2);
first.setX(2);
first.setY(2);
myConsole.printf("New X of first circle is ", first.getX(), "/n");
myConsole.printf("New Y of first circle is ", first.getY(), "/n");
myConsole.printf("New Radius of first circle is ", first.getRadius(), "/n");
Circle second = new Circle(-1.0,3.0,5.0);
Circle third = new Circle(1,1,1);
if (Circle.Overlap(second, third) <= 0) {
myConsole.printf("Second and third circles overlap");
}
else {
myConsole.printf("Second and third circles do not overlap");
}
myConsole.printf("New Y of first circle is ", first.getY());
Calculate and print out distance between them using the class method
myConsole.printf("Distance between first and second is : %.5g\n", Circle.Overlap(first, second));
}
}
The second program just has to demonstrate each aspect addressed in the brief I pasted at the top and I've only a rough idea of how to do this so if what I'm doing seems stupid to any of you please offer suggestions of what else I can do.
Your problem is that you're using the Console.printf() method incorrectly.
The first parameter to this method should be a format, and it has to have placeholders inside it for the other parameters. Read up on it in The Java Platform documentation. In fact, you should familiarize yourself with the Java platform documentation. You need to use it often to make sure you're calling methods correctly or what methods are available in a given class.
So, your printout lines should actually have been:
myConsole.printf("Circumference of first circle is %.2f%n", first.Circumference());
myConsole.printf("Area of first circle is %.2f%n", first.Area());
...etc.
The format %.2f means "The corresponding parameter is a floating-point number. Display it with a precision of 2 digits after the decimal point". The %n replaces your "\n" - the whole "template" of the print should be just in the format string. And in this type of format, one should use %n instead of \n.
I'm not sure why you opted for using the system console rather than the usual System.out.println(). If you choose to go with System.out, there is also a printf() method there that works exactly as Console.printf() - the first parameter is a format, the others are embedded in it.
One last comment: there are conventions when writing Java code:
Indent your code properly
Class names' first letter is always uppercase.
Non-constant fields and local variable names' first letter is always lowercase.
Method names also start with a lowercase letter.
Related
public Class Point{
private double x;
private double y;
public Point() {
super();
}
public Point(double x, double y) {
super();
this.x = x;
this.y = y;
}
public static Point deepCopy(Point p2) {
Point point2 = new Point(p2.x+2, p2.y+2);
return point2;
}
public static Point shallowCopy(Point p4){
return p4;
}
public void setPoint3X(double x3) {
this.x = x+1;
}
public void setPoint3Y(double y3) {
this.y = y+1;
}
public void setPoint2(double x2, double y2) {
this.x = x2+2;
this.y = y2+2;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
#Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
public class PointDemo {
public static void main(String[] args) {
double x = 0;
double y = 0;
Point point1 = new Point(5, 10);
Point point2 = Point.deepCopy(point1);
Point point3 = Point.deepCopy(point2);
point3.setPoint3X(x);
point3.setPoint3Y(y);
Point point4 = new Point();
point4 = Point.shallowCopy(point3);
Question 4 -
Write a class called Point. The class has two instance fields: x and y, both are of double type.
Write two constructors: one that uses x and y values for a point, and the other uses the first point values to create a second Point object with the exact same x and y values. Write a Demo class to build the following four Point objects.
Point 1: (x=5, y=10)
Point 2: (x=7, x=12). This point needs to be built using the deep copy constructor that copies point 1 and then using only one setter method.
Point 3: (x=10, y=15). This point needs to be built using the deep copy method that uses Point 2 as the original and then using two setter methods to change the required x and y values.
Point 4: This point needs to be built using the shallow copy method and it must use Point 3 as the shallow copy template.
Finally print all four points using one statement.
Okay. So my code gives me all the values from point1-point4 however, I cannot figure out a way to print them all in one statement. Obviously a loop in the demo class can print every Point object but that would be multiple print statements which violates the one print statement requirement.
Also, I cannot use an array in the Point class because it violates the 2 fields requirement.
Can anybody help or give me a suggestion as to how I can take all the Point objects and print it in one statement? Or is that even possible and maybe I am reading the question wrong?
You can use PrintStream.format(format(String format, Object... args):
System.out.format("(%f, %f), (%f, %f), (%f, %f), (%f, %f)\n", point1.x, point1.y, point2.x, point2.y, ...and so on);
I'm going to post this as an answer too since I think it might be what your instructor actually wants.
The key point here is to remember that the toString() method on your class can be used like a regular string and concatenate other strings, and that's what you normally do with + when calling println(). So just use the normal println() method like you've probably been doing already.
System.out.println( "Point 1 - " + point1.toString() + ";\n"
+ "Point 2 - " + point2.toString() + ";\n"
+ "Point 3 - " + point3.toString() + ";\n"
+ "Point 4 - " + point4.toString() + ";" );
You can use streams:
Arrays.stream(new Point[] {point1, point2, point3, point4}).forEach(System.out::println);
or String.format()
System.out::println(String.format("%s %s %s %s", point1, point2, point3, point4));
My assignment is to create main class in which I initialize the value of any point to be at (0,0,0) and to be able to access and mutate all three values (x,y,z) individually. To do this I have used getters and setters. My next task is to create a method within my main class (which I shall call "distanceTo") that calculates the distance between two points.
How do I go about creating the method "distanceTo" that calculates the distance between two points by taking in the x,y,z coordinates ? I assume my answer will have something to do with sqrt((x1-x2)^2+(y1-y2)^2+(z1-z2)^2) but I do not know how I can write that in my method in my main class if my points are not defined until my second test point class
So far I only have two points, but I am looking for a more general answer (so that if I created three points, p1 p2 and p3, I could calculate the distance between p1 and p2 or the distance between p2 and p3 or the distance between p1 and p3.
My main class:
package divingrightin;
public class Point3d {
private double xCoord;
private double yCoord;
private double zCoord;
public Point3d(double x, double y, double z){
xCoord = x;
yCoord = y;
zCoord = z;
}
public Point3d(){
this (0,0,0);
}
public double getxCoord() {
return xCoord;
}
public void setxCoord(double xCoord) {
this.xCoord = xCoord;
}
public double getyCoord() {
return yCoord;
}
public void setyCoord(double yCoord) {
this.yCoord = yCoord;
}
public double getzCoord() {
return zCoord;
}
public void setzCoord(double zCoord) {
this.zCoord = zCoord;
}
//public double distanceTo(double xCoord, double yCoord, double zCoord ){
}
My class with the test points:
package divingrightin;
public class TestPoints {
public static void main(String[] args) {
Point3d firstPoint = new Point3d();
firstPoint.setxCoord(2.2);
firstPoint.setyCoord(1);
firstPoint.setzCoord(5);
//System.out.println(firstPoint.getxCoord());
Point3d secondPoint = new Point3d();
secondPoint.setxCoord(3.5);
secondPoint.setyCoord(22);
secondPoint.setzCoord(20);
}
}
As #Dude pointed out in the comments, you should write a method:
public double distanceTo(Point3d p) {
return Math.sqrt(Math.pow(x - p.getxCoord(), 2) + Math.pow(y - p.getyCoord(), 2) + Math.pow(z - p.getzCoord(), 2));
}
Then if you want to get the distance between 2 points you just call:
myPoint.distanceTo(myOtherPoint);
//or if you want to get the distance to some x, y, z coords
myPoint.distanceTo(new Point3d(x,y,z);
You could even make the method static and give it 2 points to compare:
public static double getDistance(Point3d p1, Point3d p2) {
return Math.sqrt(Math.pow(p1.getxCoord() - p2.getxCoord(), 2) + ...
}
P.S. my first answer :)
public double distanceTo(Point3d other) {
return Math.sqrt(Math.pow(this.xCoord-other.getxCoord(), 2)
+ Math.pow(this.yCoord-other.getyCoord(), 2)
+ Math.pow(this.zCoord-other.getzCoord(), 2));
}
Add this to your Point3d class. When you need to calculate the distance in the TestPoints class, you do something like
double distance = firstPoint.distanceTo(secondPoint);
You have two possible approaches, according to what you want to achieve.
You can put your "distanceTo" method inside the class Point3D:
public class Point3d {
...
public double distanceTo(Point3d ) {
return Math.sqrt( Math.pow(this.x - that.x, 2) + Math.pow(this.y - that.y, 2) + Math.pow(this.z - that.z, 2));
}
In this case, you are always using the first point as the first argument, and any other point as the one you want to compute the distance from.
Alternatively, you can have a generic distanceTo method that lives somewhere(such as in your Program class, where you have your main method), that takes two points and compute the distance between those:
public class Program {
static public void main(String[] args) {}
public double distanceTo(Point3d p1, Point3d p2) {
return Math.sqrt( Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2) + Math.pow(p1.z - p2.z, 2));
}
}
Which one is better? Depends on how you use them in the common case :)
Just use the getters
float distance = Math.sqrt(Math.pow(secondPoint.getXCoord() - firstPoint.getXCoord()), 2) + ...)
Two ideas.
Either add a:
public double distanceTo(Point3d otherPoint) {
// return distance by using this.getxCoord(), this.getyCoord(), etc.
// and otherPoint.getxCoord(), otherPoint.getyCoord()
}
method to your Point3d class.
Then, at the end of your main method, you can do:
System.out.println(firstPoint.distanceTo(secondPoint));
System.out.println(tenthPoint.distanceTo(ninthPoint));
Or, add a static method to your main TestPoints class:
public static double distanceBetween(Point3d point1, Point3d point2) {
// return distance by using point1.getxCoord(), etc. and point2.getxCoord()
}
Then, at the end of your main method, you can do:
System.out.println(distanceBetween(firstPoint, secondPoint));
System.out.println(distanceBetween(tenthPoint, ninthPoint));
I have been looking at my source code and can't figure out what is wrong with it.
The problem I think is with the Circle class. When I call the mutators and accessors from
the DriverCircle class it's giving me the wrong output. For getDiameter it's just printing out 0s.
public class Circle{
private double radius;
private double pi;
private double diameter;
private double circumference;
private double area;
public Circle(){
pi = Math.PI;
radius = 0;
}
public Circle(double radius){
this.radius = radius;
}
public void setDiameter(){
diameter = (2 * radius);
}
public double getDiameter(){
//diameter = 2 * radius;
return diameter;
}
public void setCircumference(){
circumference = (2 * pi * radius);
}
public double getCircumference(){
//circumference = 2 * pi * radius;
return circumference;
}
public double getArea(){
//area = pi * Math.pow(radius, 2);
return area;
}
public void setArea(){
area = (pi * Math.pow(radius, 2));
}
public void setRadius(double radius){
this.radius = radius;
}
public double getRadius(){
return radius;
}
public String toString(){
return "The radius is " + radius;
}
}
(The tester)...
import java.util.Scanner;
public class CircleDriver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the radius: ");
Circle[] circles = new Circle[10];
Circle objectCircle = new Circle();
objectCircle.setRadius(input.nextDouble());
circles[1] = new Circle();
circles[2] = new Circle(2.0);
circles[3] = new Circle(3.5);
circles[4] = new Circle(5.0);
circles[5] = new Circle(0.0);
circles[6] = new Circle(15);
circles[7] = new Circle(25);
circles[8] = new Circle(-7);
circles[9] = new Circle(-10.0);
System.out.println("Initial call to toString():");
for (Circle c : circles)
{System.out.println("\t" + c);}
System.out.println("Call to getRadius (should be same as above):");
for (Circle r : circles)
{if (r != null)
{System.out.println("\t" + r.getRadius());}}
System.out.println("Call to getDiameter (should be twice the value shown above):");
for (Circle d : circles)
{if (d != null)
{System.out.println("\t" + d.getDiameter());}}
System.out.println("Calls to getCircumference:");
System.out.println("\tShould be 2 * PI: " + circles[1].getCircumference());
System.out.println("\tShould be 0.0: " + circles[5].getCircumference());
System.out.println("\nCall to getArea:");
System.out.println("\tShould be PI: " + circles[1].getArea());
System.out.println("\tShould be 0.0: " + circles[5].getArea());
System.out.println("Testing out the setRadius method:");
for (int i = 0; i < circles.length / 2; i++)
{if (circles[i] != null)
{circles[i].setRadius(i);}}
System.out.println("Call to toString after setting the first half of the objects:");
for (Circle c : circles)
{System.out.println("\t" + c);}
}
}
Your setter methods should have parameters and use the parameters to set fields. Else they are not in fact setter methods. Your current setter methods should all be discarded, except perhaps setRadius(...), and most of the calculations be done in the respective getter methods.
i.e., not
public void setCircumference(){
circumference = (2 * pi * radius);
}
public double getCircumference(){
//circumference = 2 * pi * radius;
return circumference;
}
but rather
public double getCircumference(){
return 2 * Math.PI * radius;
}
pi isn't initialized when you provide a value in constructor. Further, storing pi as an instance member is a bit weird. Just user Math.PI in your calculations.
You never call setDiameter(). Your constructor sets the value of the radius, but it doesn't do anything about setting the diameter variable!
You may just want to rewrite getDiameter():
public double getDiameter() {
return 2.0 * radius;
}
You constructed a Circle object, which sets the radius, but you never set the diameter. Should probably call setDiameter() from the constructor.
Better yet, delete the setDiameter() method as it's completely unnecessary. Simply make getDiameter() return 2*radius.
I see two problems.
First, and foremost, you don't set the value of pi if you use the double constructor. You should also use the no-args constructor as well as set the value of your radius:
public Circle(double radius){
this(); // calls the no-args constructor
this.radius = radius;
}
Second, there's no explicit call to setDiameter(). Funnily enough, that method is a misnomer - it should be calculated whenever the radius is nonzero. setArea is the same way - you're not passing anything in to that method call. Here's what I would recommend:
Rename setDiameter to calculateDiameter to make its intention clear. The reason for the rename is to have this class follow JavaBean conventions with respect to set and get.
In public Circle(double radius), call calculateDiameter() immediately afterwards.
Whenever setRadius() is called, either immediately follow it with a call to calculateDiameter or violate JavaBean conventions and call it immediately after the value is set.
It's strongly encouraged to do the same thing for getArea, but I'll leave that portion as an exercise to the reader.
In code, a brief example:
public Circle(double radius){
this(); // calls the no-args constructor
this.radius = radius;
calculateDiameter();
}
public void setRadius(double r) {
radius = r;
calculateDiameter();
}
Just setting the radius does not update every function that uses radius; you have to call those functions explicitly or else they remain at Java's default of 0.
I would also do any error checking at the Circle(radius) method; that way no negative numbers make it into the set of radii.
We are learning how to use multiple classes in Java now, and there is a project asking about creating a class Circle which will contain a radius and a diameter, then reference it from a main class to find the diameter. This code continues to receive an error (mentioned in the title)
public class Circle
{
public CircleR(double r)
{
radius = r;
}
public diameter()
{
double d = radius * 2;
return d;
}
}
Thanks for any help, -AJ
Update 1:
Okay, but I shouldn't have to declare the third line public CircleR(double r) as a double, right? In the book I am learning from, the example doesn't do that.
public class Circle
{
//This part is called the constructor and lets us specify the radius of a
//particular circle.
public Circle(double r)
{
radius = r;
}
//This is a method. It performs some action (in this case it calculates the
//area of the circle and returns it.
public double area( ) //area method
{
double a = Math.PI * radius * radius;
return a;
}
public double circumference( ) //circumference method
{
double c = 2 * Math.PI * radius;
return c;
}
public double radius; //This is a State Variable…also called Instance
//Field and Data Member. It is available to code
// in ALL the methods in this class.
}
As you can see, the code public Circle(double r).... how is that different from what I did in mine with public CircleR(double r)? For whatever reason, no error is given in the code from the book, however mine says there is an error there.
As you can see, the code public Circle(double r).... how is that
different from what I did in mine with public CircleR(double r)? For
whatever reason, no error is given in the code from the book, however
mine says there is an error there.
When defining constructors of a class, they should have the same name as its class.
Thus the following code
public class Circle
{
//This part is called the constructor and lets us specify the radius of a
//particular circle.
public Circle(double r)
{
radius = r;
}
....
}
is correct while your code
public class Circle
{
private double radius;
public CircleR(double r)
{
radius = r;
}
public diameter()
{
double d = radius * 2;
return d;
}
}
is wrong because your constructor has different name from its class. You could either follow the same code from the book and change your constructor from
public CircleR(double r)
to
public Circle(double r)
or (if you really wanted to name your constructor as CircleR) rename your class to CircleR.
So your new class should be
public class CircleR
{
private double radius;
public CircleR(double r)
{
radius = r;
}
public double diameter()
{
double d = radius * 2;
return d;
}
}
I also added the return type double in your method as pointed out by Froyo and John B.
Refer to this article about constructors.
HTH.
Every method (other than a constructor) must have a return type.
public double diameter(){...
You forgot to declare double as a return type
public double diameter()
{
double d = radius * 2;
return d;
}
I had a similar issue when adding a class to the main method. Turns out it wasn't an issue, it was me not checking my spelling. So, as a noob, I learned that mis-spelling can and will mess things up. These posts helped me "see" my mistake and all is good now.
I'm trying to call angles from from the angle method down below in the Rotate90 method but I'm not sure of the syntax. What is the correct syntax?
import java.lang.Math;
public class CartesianPoint implements Point
{
private double xCoord;
private double yCoord;
public CartesianPoint (double xCoordinate,double yCoordinate)
{
xCoord = xCoordinate;
yCoord = yCoordinate;
}
public double xCoordinate ()
{
return xCoord;
}
public double yCoordinate ()
{
return yCoord;
}
public double angle ()
{
double angles;
angles = Math.cos( xCoord / Math.sqrt( xCoord*xCoord + yCoord*yCoord));
return angles;
}
public double radius ()
{
double radius;
radius = (yCoord*yCoord + xCoord*xCoord); //?
return radius;
}
public Point rotate90()
{
double rotated;
rotated = angles.angle + 90.0; //██████████ Error here ██████████
return rotated;
}
public double distanceFrom(Point other)
{
return 0;
}
}
I think you mean
rotated = angle() + 90.0;
Except I think you'll find that Math.cos uses radians not degrees, so you're not going to get the result you think you are. And shouldn't that be arc cos, not cosine? Something like this might be more what you're looking for:
public double angle()
{
return Math.atan2(ycoord, xcoord) * 180 / Math.PI;
}
If you want rotate90 to return a new Point that is 90 degrees from the current point, then change it to the following:
public Point rotate90()
{
return new CartesianPoint(-yCoord, xCoord);
}
Method invocations in Java always have trailing parentheses even when they don't have any arguments:
rotated = angle() + 90.0;
Method call requires parenthesis even if there are no parameters needed. This is different from other languages, e.g.groovy.
To answer your question directly: If you want to be able to access the variable "angles" from outside the "angle" function, you must make it a class variable. That is, declare it outside of any function, like you have declared xCoord and yCoord. Then refer to it by its simple name without any reference to the function that created it.
Note that if rotate90 tries to reference angle before angles() is called, angle will contain zero (or whatever default value you set) and is unlikely to be useful.
It's not clear to me exactly what you're trying to accomplish. I think that your intent is that the angles function would take the arc cosine, not the cosine.