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.
Related
I'm new to coding and I'm currently working with OOP in Java. My instructor had us create a rectangle class instead of just importing the built-in. Anyway, we were to create constructors featuring ints and doubles as parameters. My questions is, with having two constructors if different data types, do I need separate getters / setters for each type? Would this be a time I could use generic datatypes? I have included what I created below. Thanks.
public class Rectangle {
private int height;
private int width;
private double doubleHeight;
private double doubleWidth;
public Rectangle() {
height = 0;
width = 0;
}
public Rectangle(int h, int w) {
height = h;
width = w;
System.out.println("A Rectangle has been created using integer dimensions.");
}
public Rectangle(double h, double w) {
doubleHeight = h;
doubleWidth= w;
System.out.println("A Rectangle has been created using double dimensions.");
}
public int getIntHeight() {
return height;
}
public double getDoubleHeight() {
return doubleHeight;
}
public int setIntHeight(int h) {
height = h;
}
public double setDoubleHeight(double h) {
doubleHeight = h;
}
public int getIntArea() {
return width * height;
}
public double getDoubleArea() {
return doubleWidth * doubleHeight;
}
public int getIntPerimeter() {
return width*2 + height*2;
}
public double getDoublePerimeter() {
return doubleWidth*2 + doubleHeight*2;
}
public String toString() {
if (this.getIntHeight() >= 1) {
return "Height: " + height + ", Width: " + width;
}
else {
return "Height: " + doubleHeight + ", Width: " + doubleWidth;
}
}
}
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());
}
}
}
I recently started learning Java and I'm having some trouble understanding how to make arrays to work the way I want them to.
Here I have an assignment of creating a polygon class with different methods inside.
Basically the class represents a convex polygon in a plane.
The array receives user input that consists of x and y coordinates and places them inside. (max number of vertices is 10).
There are some functions that I have no idea how to do and I would really appreciate some help with.
Point Class - which is used to get coordinates
public class Point {
private double _x;
private double _y;
public Point() {
this._x = 0.0D;
this._y = 0.0D;
}
public Point(double x, double y) {
this._x = x;
this._y = y;
}
public Point(Point other) {
this._x = other._x;
this._y = other._y;
}
public double getX() {
return this._x;
}
public double getY() {
return this._y;
}
public void setX(double x) {
if (x >= 0.0D)
this._x = x;
}
public void setY(double y) {
if (y >= 0.0D)
this._y = y;
}
public boolean isAbove(Point other) {
return (this._y > other._y);
}
public boolean isUnder(Point other) {
return other.isAbove(this);
}
public boolean isLeft(Point other) {
return (this._x < other._x);
}
public boolean isRight(Point other) {
return other.isLeft(this);
}
public double distance(Point other) {
double distance = Math.sqrt(Math.pow(this._x - other._x, 2.0D) + Math.pow(this._y - other._y, 2.0D));
return distance;
}
public void move(double dx, double dy) {
double x = this._x + dx;
double y = this._y + dy;
if (x >= 0.0D && y >= 0.0D) {
this._x = x;
this._y = y;
}
}
public boolean equals(Point other) {
return (this._x == other._x && this._y == other._y);
}
public String toString() {
return "(" + this._x + "," + this._y + ")";
}
}
Polygon Class - main class im working on
/**
* Write a description of class Polygon here.
*
* #author [REDACTED]
* #version (Ver 1.0)
*/
public class Polygon {
private Point[] _vertices;
private int _noOfVertices;
public Polygon() {
_vertices = (Point[]) new Point[10];
_noOfVertices = 0;
}
public Polygon(Point[] arr) {
_vertices = (Point[]) new Point[10];
_noOfVertices = 0;
if (arr.length > 10) {
return;
}
// for (Point P : arr)
for (int i = 0; i < arr.length; i++) {
if (arr[i] != null) {
_vertices[i] = arr[i];
_noOfVertices++;
}
}
}
public boolean addVertex(double x, double y) {
if (_noOfVertices >= 10)
return false;
Point p = new Point(x, y);
_vertices[_noOfVertices] = p;
_noOfVertices++;
return true;
}
public Point highestVertex() {
for (int i = 0; i < _noOfVertices; i++) {
}
}
public String toString() {
}
public double calcPerimeter() {
for (int i = 0; i < arr.length; i++) {
}
}
public double caclArea() {
Point ppp = _vertices[zzz]
}
public boolean isBigger(Polygon other) {
}
public int findVertex(Point p) {
for (int i = 0; i < _noOfVertices; i++) {
if (p.equals(_vertices[i])) {
return i;
}
}
return -1;
}
public Point getNextVertex(Point p) {
for (int i = 0; i < _noOfVertices; i++) {
if (p.equals(_vertices[i])) {
if (i == _noOfVertices - 1) {
return new Point(_vertices[0]);
}
return new Point(_vertices[i + 1]);
}
}
return null;
}
public Polygon getBoundingBox() {
}
}
I have no idea how to do these functions:
Line 44: public Point highestVertex() {} - returns a copy of the highest point in the polygon. If there is more than one vertice at the same Y - the method will return the first one it encountered (with the said Y) If there are no vertices aka the array is empty it will return null.
Line 52: public String toString() {} - method that returns a string of points representing the polygon. The string should be in the following format:
The polygon has 5 vertices:
((2.0,1.0),(5.0,0.0),(7.0,5.0),(4.0,6.0),(1.0,4,0))
If there are no vertices the method will return a string in the following format:
The polygon has 0 vertices.
English is not my first language so I apologize for any grammar mistakes in advance.
First, it's not really the best to ask homework questions here, this is a concept that you should learn.
In highestVertex(), they outline the 3 cases for you:
1st case: If point-y is equal to another point-y, return the first vertex that has point-y.
2nd case: if arr has no elements return null.
3rd case: in loop, check each element's y value in the array and compare it to the biggest y so far.
Use this line before your loop:
int max = Integer.MIN_VALUE;
Inside loop:
if (arr[i] > max) max = arr[i]
For toString(), again loop throughout the array, and add each point to a tracker string that you will return.
String str = "";
loop
str += arr[i].toString() + ",";
This works except you need to loop until arr's second to last element, as you will have an extraneous comma after the last point.
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);
So for this project I wish to input an array containing a number of points. (no specific number). I am confused on how I should approach the methods and constructor because some of the methods call for changes such as grabbing the average of the X or Y values. Am I approaching this project in the right way? Should I be using a clone of the point list, or an array list or what... (note I am only showing part of the PolygonImpl class as an example, they all function similarly) The class point contains :
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 double getY() {
return y;
}
public Point translate(double dx, double dy) {
return new Point(x+dx, y+dy);
}
public double distanceTo(Point p) {
return Math.sqrt((p.x - x)*(p.x -x) + (p.y-y)*(p.y-y));
}
}
public class PolygonImpl implements Polygon {
private double xSum=0;
private double ySum=0;
private ArrayList<Point> points;
private Point[] pList;
private Point a;
PolygonImpl(Point[] pList) {
this.pList = pList.clone();
points = new ArrayList<Point>();
for (int index = 0; index < pList.length; index++) {
points.add(pList[index]);
xSum += pList[index].getX();
ySum += pList[index].getY();
}
}
public Point getVertexAverage() {
double xSum = 0;
ArrayList<Point> vlist = new ArrayList<Point> ();
double ySum = 0;
for (int index = 0; index < vlist.size(); index++) {
xSum = xSum + vlist.get(index).getX();
ySum = ySum + vlist.get(index).getY();
}
return new Point(xSum/getNumSides(), ySum/getNumSides());
}
public int getNumSides() {
return pList.length;
}
public void move(Point c) {
Point newCentroid = new Point(a.getX()+ c.getX(), a.getY() +c.getY());
}
public void scale(double factor) {
ArrayList<Point> points = new ArrayList<Point> ();
for (int index = 0; index < pList.length; index++) {
{ double x = pList[index].getX() *factor;
double y = pList[index].getY() * factor;
Point a = new Point(x,y);
points.add(index,a);
}
}
}
In this case, I don't think you need the extra List objects; they are redundant.
Here is the code just using the pList array.
public class PolygonImpl implements Polygon {
private double xSum=0;
private double ySum=0;
private Point[] pList;
private Point a;
PolygonImpl(Point[] pList) {
this.pList = pList.clone();
for (int index = 0; index < pList.length; index++) {
xSum += pList[index].getX();
ySum += pList[index].getY();
}
}
public Point getVertexAverage() {
double xSum = 0;
double ySum = 0;
for (int index = 0; index < pList.length; index++) {
xSum = xSum + pList[index].getX();
ySum = ySum + pList[index].getY();
}
return new Point(xSum/getNumSides(), ySum/getNumSides());
}
public int getNumSides() {
return pList.length;
}
public void move(Point c) {
Point newCentroid = new Point(a.getX()+ c.getX(), a.getY() +c.getY());
}
public void scale(double factor) {
for (int index = 0; index < pList.length; index++)
{
double x = pList[index].getX() *factor;
double y = pList[index].getY() * factor;
Point a = new Point(x,y);
pList[index] = a;
}
}
There are at least three things here that need pointing out.
The first is the difference between "clone" and "copy." .clone is a shallow copy; that means if you change the clone, you also change the original.
The second is regarding your use of collections. Since a polygon is a collection of points, either an array or an ArrayList would be approriate, but there is no point in using bother, or, if there is, think long and hard about whether it's a good point, and then explain in the inline documentation why it matters, else it will come back to bite you in the form of using one when you mean the other.
Third is scope. Your polygon class has instance variables (xSum and ySum) that are occluded by variables with the same name in getVertexAverage. The way they are used in getVertexAverage is appropriate in itself; the instance variables are only useful if you mean to cache the sums, which becomes more questionable, because every operation that changes a point invalidates the instance values.
Instance values are for storing data about an object (in this case, points are reasonable); instance methods are for operating on that data at a given state (in this case, the average).
Keeping this in mind, you can now understand how the move method isn't finished :)