This question already has answers here:
Non-static method requires a target
(8 answers)
Closed 6 years ago.
I have 3 classes: Point, Polygon and ClientePolygon. Point creates an object, Point(double x, double y) with many nonstatic methods. Polygon creates an array of Point with non-static methods, i.e., write, move, and return the Point closest to the origin in the array. ClientePolygon executes Polygon. The problem is that when I run ClientePolygon it gives me Point class executed... and I want to run Polygon. Any suggestions? Thanks a lot.
ClientePolygon:
package k;
public class ClientePolygon {
public void main(String [] args){
Point origem = new Point (0,0);
Point [] vertices = new Point[4];
vertices[0] = new Point (1.0,1.0);
vertices[1] = new Point (1.0,5.0);
vertices[2] = new Point (2.0,5.0);
vertices[3] = new Point (2.0,1.0);
for (int i = 0; i < vertices.length; i++) {
vertices[i].translate(5.0,7.5);
}
}
}
Point:
package k;
public class Point {
private double x;
private double y;
public Point(double x, double y){
this.x = x;
this.y = y;
}
public double getX(){
return x;
}
public String toString(){
return "("+ this.x+", "+this.y+")";
}
public Point copy(){
Point copia = new Point(x, y);
return copia;
}
public static double distance(Point ponto1, Point ponto2){
double distX = ponto1.x + ponto2.x;
double distY = ponto1.y + ponto2.y;
return Math.sqrt(distX*distX + distY*distY);
}
public void translate(double dx, double dy){
double transX = this.x + dx;
double transY = this.y + dy;
System.out.println(toString()+" fica "+ transX +" e "+ transY);
}
public static void main(String[] args) {
Point ponto1 = new Point(2,1);
Point ponto2 = new Point(3,9);
System.out.println(ponto1.toString());
System.out.println(ponto2.toString());
System.out.println("A distancia entre os pontos eh: " +distance(ponto1, ponto2));
System.out.println("O ponto copiado eh: "+ponto2.copy());
ponto2.copy().translate(2, 3);
}
}
Polygon:
package k;
public class Polygon {
private Point [] vertices;
public Polygon(Point [] vertices){
this.vertices = vertices;
}
public String toString(){
return "Ponto 1 em: "+vertices;
}
public Point closestToOrigin(){
Point proximo = new Point(0, 0);
Point origem = new Point(0,0);
for (int i = 0; i < vertices.length; i++) {
double distancia = Point.distance(vertices[i], origem);
if(distancia<Point.distance(vertices[i-1], origem)){
proximo = vertices[i];
}
}
return proximo;
}
public void translate(double dx, double dy){
Point Trans = new Point(dx, dy);
System.out.println("Ponto 1 fica: "+vertices[0]+Trans+", Ponto 2 fica: "+vertices[1]+Trans+" e Ponto 3 fica: "+vertices[2]+Trans);
}
}
To call a nonstatic method you need to instantiate the other class by doing
Class object = new Class(parameters);
and then call the method on that object:
object.method();
You must instantiate the Polygon class before calling a nonstatic method:
Polygon poly = new Polygon(vertices);
Then you can do:
poly.translate(5.0,7.5);
Related
I have a simple class 2Dpoints with two fields, x and y. I want to write a code so that I could command one point to moves slowly to another point, like so that it moves on the vector line of their distances. But I don't know how?
I've first thought that it should contain a for loop so that it would know, it should move till it reaches the other point
something like for(int d=0 ; d<distance ; d++) but I don't know how should I then command it so that it would move on the line?
import java.lang.Math.*;
public class Punkt {
private int x;
private int y;
public Punkt(int x, int y) {
this.x=x;
this.y=y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int distance) {
x = x + distance;
}
public void setY(int distance) {
y = y + distance;
}
public void moveAbout(int dx, int dy) {
x = x + dx;
y = y + dy;
}
/// method for calculating the distance to another point
public double giveDistance(Punkt otherPoint) {
return Math.sqrt(
(otherPoint.getY() - y) *
(otherPoint.getY() - y) +
(otherPoint.getX() - x) *
(otherPoint.getX() - x));
}
}
I've commented the major lines:
import static java.lang.Math.*;
/**
* Immutable structure. Functional way
*/
class Point {
public final double x;
public final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
/**
* Here you are. This is what you want to implement.
* from.moveTo(0.0, to) => from
* from.moveTo(1.0, to) => to
*
* #param by - from 0.0 to 1.0 (from 0% to 100%)
* #param target - move toward target by delta
*/
public Point moveTo(double by, Point target) {
Point delta = target.sub(this);
return add(delta.dot(by));
}
public Point add(Point point) {
return new Point(x + point.x, y + point.y);
}
public Point sub(Point point) {
return new Point(x - point.x, y - point.y);
}
public Point dot(double v) {
return new Point(v * x, v * y);
}
public double dist(Point point) {
return sub(point).len();
}
public double len() {
return sqrt(x * x + y * y);
}
public String toString() {
return x + ":" + y;
}
}
class Main {
public static void main(String[] args) {
Point source = new Point(2, 3);
Point target = new Point(-4, 9);
// You can utilize the cycle or implement kind of timer to animate something
for (int t = 0; t <= 100; t++) {
System.out.println(source.moveTo(0.01 * t, target));
}
}
}
https://replit.com/join/sucvdhpqoa-redneckz
#AlexanderAlexandrov I've change the type of my variables to double accordingly, now in one of my classes I have a method givePoints, which uses Scanner for asking a user how many points he wants and what are the coordinates then it saves them into an array of points with first element being always(0,0).
Another method takes an array of points as parameter and sort them in order of their distances to point(0,0).
These methods work perfectly. The problem is with method hitThepoints.
Here I want to first create the array of points, sort them, and then command my robot to hit all the points. robot is an object of class Robot extends circle, with position of type Point, that at first is at point(0,0)
public void hitThePoints(){
Point[] poi=sortPoints (givePoints()); //Creates a sorted array of points
Point short=new Point(poi[1].getX(),poi[1].getY());
System.out.println(" the nearest point is :");
System.out.println("("+short.getX()+ ","+short.getY()+")");
for(int i=1; i<poi.length;i++){
Point source=robot.position;
Point target=new Point(poi[i].getX(), poi[i].getY());
while(source.getX()!=target.getX() &&
source.getY()!=target.getY()){
robot.bewegeUm((source.moveTo(0.01,target)).getX(),
(source.moveTo(0.01,target)).getY());
if(source.getX()!=target.getX() &&
source.getY()!=target.getY()){break;}
System.out.println(source.getX() +","+ source.getY());
}
}
}
Alright so I have created 2 methods called Point and LineSegment (they both work).
Point is this:
public class Point {
private double x;
private double y;
public Point(){
x=0;
y=0;
}
public Point(double a, double b){
x=a;
y=b;
}
public double getY(){
return y;
}
public double getX(){
return x;
}
public void setX(double newX){
x= newX;
}
public void sety(double newY){
y= newY;
}
public void setXY(double newX, double newY){
x = newX;
y = newY;
}
public String toString(){
return "("+x+" , "+y+")";
}
}
LineSegment is this :
public class LineSegment {
private Point A;
private Point B;
public LineSegment (){
A = new Point();
B = new Point();
}
public LineSegment (int x1, int y1, int x2, int y2){
A = new Point(x1, y1);
B = new Point(x2, y2);
}
public LineSegment(Point P, Point Q){
A = new Point(P.getX(), P.getY());
B = new Point(Q.getX(), Q.getY());
}
public double Length(){
double length = Math.sqrt(Math.pow( (B.getX() - A.getX()), 2) + Math.pow((B.getY() - A.getY()),2));
return length;
}
public double Slope(){
double slope = (B.getY() - A.getY() )/ (B.getX() - A.getX());
return slope;
}
public String toString(){
return "("+A.getX()+" , "+A.getY()+") + ("+B.getX()+" , "+B.getY()+") ";
}
}
As I said both of these codes work but now my task is to use Linesegment to create 2 line segments called AB and CD, and to output the slope of both of them, I am not sure how to do this, can anybody help?
They are called classes, not methods.
And you've already made class instances in your LineSegment class at
A = new Point();
B = new Point();
So now, in some other class,
public static void main(String[] args) {
Point A = new Point();
Point B = new Point();
Point C = new Point();
Point D = new Point();
LineSegment AB = new LineSegment(A, B);
LineSegment CD = new LineSegment(C, D);
// output the slope
System.out.println(AB.Slope());
}
Also, note that your Slope method will return a divide-by-zero error if you run this code as-is.
Create a class, regardless of its name, and put the main method.
The method called main is essentially your starting point, where your code will start running.
public static void main(String[]args){
LineSegment segment1 = new LineSegment(1,2,3,4);
LineSegment segment2 = new LineSegment(5,6,7,8);
System.out.println("The first slope is: " + segment1.Slope());
System.out.println("The second slope is: " + segment2.Slope());
}
What do I do wrong? I get incorrect results (coordinates).
A triangle (see the picture below: blue is the original triangle, lime is the rotated one: a clone. Edge A is a fixed point).
The classes I use:
A Point class:
public class Point {
private final double x;
private final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
#Override
public String toString() {
return "[(" + x + ") (" + y + ")]";
}
}
An abstract Object2D class:
public abstract class Object2D {
Point[] point;
public Point getPoint(int i) {
return point[i];
}
public double getLowestX() {
return Arrays.asList(point).stream()
.mapToDouble(Point::getX)
.min().getAsDouble();
}
public double getHighestX() {
return Arrays.asList(point).stream()
.mapToDouble(Point::getX)
.max().getAsDouble();
}
public double getLowestY() {
return Arrays.asList(point).stream()
.mapToDouble(Point::getY)
.min().getAsDouble();
}
public double getHighestY() {
return Arrays.asList(point).stream()
.mapToDouble(Point::getY)
.max().getAsDouble();
}
public double getLength() {
return getSide(getLowestX(), getHighestX());
}
public double getHeight() {
return getSide(getLowestY(), getHighestY());
}
private double getSide(double v1, double v2) {
return (v1 < v2) ? (0 - v1) + v2 : (0 - v2) + v1;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Point pt : point) sb.append(pt).append("\n");
return sb.toString();
}
}
A Line class:
public class Line extends Object2D {
public Line(Point point0, Point point1) {
point = new Point[2];
point[0] = point0;
point[1] = point1;
}
public double getLineLength() {
return Math.sqrt(Math.pow(getLength(), 2) + Math.pow(getHeight(), 2));
}
}
My Triangle class:
public class Triangle extends Object2D {
public Triangle(Point point0, Point point1, Point point2) {
point = new Point[3];
point[0] = point0;
point[1] = point1;
point[2] = point2;
}
public static Triangle getRotatedTriangle(Triangle triangle) {
Point point0 = triangle.getPoint(0);
Point point1 = triangle.getPoint(1);
Point point2 = triangle.getPoint(2);
Line baseLine = new Line(point0, point1);
double rotationHeight = baseLine.getHeight();
double baseLength = baseLine.getLineLength();
double sinA = rotationHeight / baseLength;
double angle = Math.asin(sinA);
double cosA = Math.cos(angle);
point1 = new Point(
(point1.getX() * cosA - point1.getY() * sinA),
(point1.getX() * sinA + point1.getY() * cosA));
point2 = new Point(
(point2.getX() * cosA - point2.getY() * sinA),
(point2.getX() * sinA + point2.getY() * cosA));
return new Triangle(point0, point1, point2);
}
}
And, of course, my main class:
public class TestDrive {
public static void main(String[] args) {
Triangle triangle = new Triangle (
new Point(-6.5, -1.5),
new Point(2.5, 7.5),
new Point(6.5, -5.5)
);
System.out.println(triangle);
System.out.println(Triangle.getRotatedTriangle(triangle));
}
}
You made 2 mistakes in your code:
You are trying to rotate with the angle α when you should be rotating with the angle -α (since you are rotating clockwise).
Your multiplication matrix is incorrect: your code will perform a rotation around the origin of the XY plane instead of rotating around the point A. For the point (x, y) rotated by the rotation matrix R around the center (a, b), the correct formula for the new rotated point (x', y') would be (x', y') = R * (x - a, y - b) + (a, b).
This should be enough for you to correct your code. As reference, here's the solution I get for the rotated triangle:
[(-6.5) (-1.5)]
[(6.227922061357855) (-1.5000000000000009)]
[(-0.1360389693210724) (-13.520815280171309)]
I am getting a null pointer exception when I try to use the perimeter function in my code. It seems that the Points array (Point is a simple object with an x and y coordinate) is not correctly initialising, I believe I may have declared the array wrongly or the constructor is incorrect.
package shapes;
import static java.lang.Math.*;
public class Triangle {
private int sides = 3;
private Point[] Points = new Point[sides];
public Triangle(Point[] vertices) {
vertices = Points;
}
public double perimeter() {
return Points[0].distance(Points[1]) + Points[1].distance(Points[2]) + Points[2].distance(Points[0]);
}
public double area() {
double semiperimeter = perimeter() / 2;
return sqrt(semiperimeter * (semiperimeter - Points[0].distance(Points[1])) * (semiperimeter - Points[1].distance(Points[2])) * (semiperimeter - Points[2].distance(Points[0])));
}
#Override
public String toString() {
return "Triangle has perimeter of " + perimeter() + " and an area of " + area();
}
public void translate(int dx, int dy) {
for(int i = 0; i < 3; i++) {
Points[i].translate(dx, dy);
}
}
public void scale(int factor) {
for(int i = 0; i < 3; i++) {
Points[i].scale(factor);
}
}
public Point getVertex(int i) {
return Points[i];
}
}
Any help is much appreciated!
You need to reverse this in your constructor:
vertices = Points;
to
Points = vertices ;
You need to initialize your Points array with the input vertices and not the other way around.
I need to implement a Triangle class and im stuck on comparing the lengths of the sides to determine if the triangle is indeed an isosceles. Here is what I have so far:
public class TriangleIsosceles {
private Point cornerA;
private Point cornerB;
private Point cornerC;
private int x1;
private int y1;
private int x2;
private int y2;
private int x3;
private int y3;
public TriangleIsosceles(){
cornerA = new Point(0,0);
cornerB = new Point(10,0);
cornerC = new Point(5,5);
}
public TriangleIsosceles(int x1,int y1,int x2,int y2,int x3,int y3){
cornerA = new Point(x1,y1);
cornerB = new Point(x2,y2);
cornerC = new Point(x3,y3);
}
public String isIsosceles(String isIsosceles){
return isIsosceles;
}
}
The Point object im using is this:
public class Point {
private int x;
private int y;
public Point(){
this(0,0);
}
public Point(int x, int y){
this.x = x;
this.y = y;
}
public void setX(int x){
this.x=x;
}
public void setY(int y){
this.y=y;
}
public void printPoint(){
System.out.println(x + y);
}
public String toString(){
return "x = "+x+" y = "+y;
}
}
In another class (LineSegment) I created a method length() that determines the distance of two points. Which looks like:
public double length() {
double length = Math.sqrt(Math.pow(x1-x2,2) + Math.pow(y1-y2,2));
return length;
}
How can I use this method to help me find the lengths of the triangle in my TriangleIsosceles class?
I know I need to see if (lenghtAB == lengthBC || lengthBC == lenghtCA || lengthAB == lengthCA).
A quick, perfectly valid, solution would be to make your length method a static utility method, i.e.
public static double length(x1, y1, x2, y2)
{
return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
}
or
public static double length(Point p1, Point p2)
{
return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
}
You could also add the method to Point itself, i.e. in the Point class add:
public double calcDistance(Point otherPoint)
{
return Math.sqrt(Math.pow(this.x - otherPoint.x, 2) + Math.pow(this.y - otherPoint.y, 2));
}
Assuming your LineSegment class has a constructor that takes two Point objects, you should create three LineSegment objects (which you can cache in the Triangle class). Then using LineSegment#getLength() you can determine if any two sides are the same length.
Since this looks like homework I won't give you the full solution.