Getting Null Pointer Exception error Null value getting passed - java

I want to create a triangle object and the get the area and perimeter of the triangle. I'm getting a NullPointerException at Triangle.area and at Demo.main. It seems like no values are being passed to the area method and perimeter method but I can't see where I've gone wrong with my code. Here's my code.
//POINTCLASS
public class Point {
private int x;
private int y;
public Point(int X, int Y){
this.x = X;
this.y = Y;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public double distance(Point p){
double distance,dx,dy;
dx=x-p.x;
dy=y-p.y;
distance = Math.sqrt((dx*dx)+(dy*dy));
return distance;
}
public void translate(int dx, int dy){
x+=dx;
y+=dy;
}
public void scale(int factor){
x*=factor;
y*=factor;
}
public String toString(){
String attributes = "x = " + x + "," + " y = " + y;
return attributes;
}
}
//TRIANGL CLASS
public class Triangle {
private int sides = 3;
private Point point1,point2,point3;
private Point[] Points;
public Triangle(Point[] vertices){
Points = vertices;
}
public Triangle(int x1,int y1,int x2,int y2,int x3, int y3){
point1 = new Point(x1,y1);
point2 = new Point(x2,y2);
point3 = new Point(x3,y3);
Points[0]=point1;
Points[1]=point2;
Points[2]=point3;
}
public double perimeter(){
double side1=point1.distance(point2);
double side2=point2.distance(point3);
double side3=point1.distance(point3);
return side1+side2+side3;
}
//issue with code seems to be here
public double area(){
double side1=point1.distance(point2);
double side2=point2.distance(point3);
double side3=point1.distance(point3);
double s = perimeter()/2;
double area = Math.sqrt(s*(s-side1)*(s-side2)*(s-side3));
return area;
}
public String toString(){
String attributes = "Sides " + sides;
return attributes;
}
public void translate(int dx, int dy){
Points[0].translate(dx,dy);
Points[1].translate(dx, dy);
Points[2].translate(dx, dy);
}
public void scale(int factor){
vertices*=factor;
}
public Point getVertex(int i){
return vertices[i];
}
}
//MAIN CLASS
public class GDemo {
public static void main(String[] args) {
Point p1 = new Point(0,20);
Point p2 = new Point(20,0);
Point p3 = new Point(30,30);
Point[] vertices = {p1,p2,p3};
Triangle t = new Triangle(vertices);
System.out.println("Triangle" + t.toString() + " area:" + t.area() +
" perimeter: " + t.perimeter());
t.translate(10, 15);
System.out.println("Triangle" + t.toString() + " area:" + t.area() +
" perimeter: " + t.perimeter());
t.scale(2);
System.out.println("Triangle" + t.toString() + " area:" + t.area() +
"perimeter: " + t.perimeter());
}
}

You are calling the constructor Triangle(Point[] vertices) while creating the Triangle Object. So your these fields are remain uninitialized private Point point1,point2,point3; And that's why you are getting NullPointerException.
Fixed constructor should be something like this:
public Triangle(Point[] vertices){
Points = vertices;
// initialize point1, point2, point3 here.
if(vertices.length > 2){
this.point1 = vertices[0];
this.point2 = vertices[1];
this.point3 = vertices[2];
}
}

You call the constructor public Triangle(Point[] vertices) and you didn't set point1, point2, and point3 values - they stay null. Because this, when in method area you try calculate double side1 = point1.distance(point2); it throws NPE.

Try putting entire code in try-catch block and catch NullPointerException and write
e.printStackTrace();
eg:
try{
//your block of code
}catch(NullPointerException e){
e.printStackTrace();
}
It would display the line number of the error code

Related

the formula gives an incorrect result (turning a point by a given angle)

I want to calculate the coordinates of the points of the triangle when rotated by 45 degrees.
I decided to use this formula.but I don't understand where I made a mistake, since I kind of wrote everything correctly.
While for the x coordinates I get the correct results, but the problem is with y.
can you tell me what I was wrong about?thank you in advance.
class Point {
Double x;
Double y;
public Point(double x, double y) {
this.setX(x);
this.setY(y);
}
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;
}
public Point() {
x=0.0;
y=0.0;
}
public String toString() {
return x + " " + y + "\n";
}
}
class Triangle{
public Point A;
public Point B;
public Point C;
public Triangle (Point _a, Point _b,Point _c) {
A=_a;
B=_b;
C=_c;
public void sd_alfa(double d) {
Point CG=new Point((A.x+B.x+C.x)/3.0,(A.y+B.y+C.y)/3.0);
A.x=CG.x+(A.x-CG.x)*Math.cos(d)-(A.y-CG.y)*Math.sin(d);
A.y=CG.y+(A.x-CG.x)*Math.sin(d)+(A.y-CG.y)*Math.cos(d);
B.x=CG.x+(B.x-CG.x)*Math.cos(d)-(B.y-CG.y)*Math.sin(d);
B.y=CG.y+(B.x-CG.x)*Math.sin(d)+(B.y-CG.y)*Math.cos(d);
C.x=CG.x+(C.x-CG.x)*Math.cos(d)-(C.y-CG.y)*Math.sin(d);
C.y=CG.y+(C.x-CG.x)*Math.sin(d)+(C.y-CG.y)*Math.cos(d);
}
public String Draw() {
return " "+"A "+ A + " "+ "B "+ B + " "+ "C "+ C;
}
}
public class EightLab {
public static void main(String[] args) {
// TODO Auto-generated method stub
Point a = new Point(1,1);
Point b = new Point(3,3);
Point c = new Point(3,1);
System.out.println("A = " + a.toString());
Triangle T = new Triangle(a, b, c);
System.out.println("Triangle = \n" + T.Draw());
//T.sd_up(2.0);
// System.out.println("Triangle = \n" + T.Draw());
T.sd_alfa(Math.toRadians(45.0));
System.out.println("Triangle = \n" + T.Draw());
}
}
My result:
A 1.8619288125423017 0.8619288125423017
B 1.8619288125423021 2.276142374915397
C 3.276142374915397 1.8619288125423017
The result I want to get:
1.8633095244169 0.25578643762691
1.8633095244169 3.0842135623731
3.27752308679 1.67

Converting class using an array of references to Point2d objects to using a java.util.ArrayList<Point2d>

package polygongeneric;
import java.util.ArrayList;
public class Polygon {
private ArrayList <Point2d> p = null;
private int points = 0;
public Polygon() { }
public Polygon(int numPoints) {
p = new ArrayList<>();
}
public boolean addPoint(Point2d point) {
p.add(points, point);
points++;
return true;
}
public boolean addPoint(double x, double y) {
Point2d a = new Point2d(x,y);
p.add(points, a);
return true;
}
#Override
public String toString() {
String s = "";
for (int i=0; i<points; i++)
s += p.get(i).toString() + "\n";
return s;
}
}
I'm trying to convert a class from using an array of references to Point2d objects as type Point2d. This is what I have so far but it's not outputting the answer that it's supposed to.
This is what my code outputs
(0.1,0.9)
(0.5,0.5)
(0.2,0.5)
This is what it's supposed to output
(0.1,0.9)
(0.3,0.7)
(0.5,0.5)
(0.4,0.8)
(0.2,0.5)
Do you guys have any idea. What I'm doing wrong?
This is my Point2d class
package polygongeneric;
public class Point2d {
private double x = 0, y = 0;
public Point2d() { }
public Point2d(double x, double y) {
setX(x);
setY(y);
}
public void setX(double initX) {
if (initX >= 0 && initX <= 1)
x = initX;
}
public void setY(double y) {
if (y >= 0 && y <= 1)
this.y = y;
}
public double getX() { return x; }
public double getY() { return y; }
public String toString() {
return "(" + x + "," + y + ")";
}
}
This is my main method
package polygongeneric;
public class PolygonGeneric {
public static void main(String[] args) {
Polygon p = new Polygon(5);
p.addPoint(new Point2d(.1, .9));
p.addPoint(.3, .7);
p.addPoint(new Point2d(.5, .5));
p.addPoint(.4, .8);
p.addPoint(new Point2d(.2, .5));
System.out.println(p);
}
}
You are not incrementing the position in your addPoint(double x, double y), so basically, you are replacing the existing point with a new point, so you are missing few point values and you need to correct the correct the code as shown below:
public boolean addPoint(double x, double y) {
Point2d a = new Point2d(x, y);
p.add(points, a);
points++;
return true;
}
Because you are simply adding the point at the end of the list, I suggest you can directly use arraylist.add(point); so that you will not get into these increment/other issues.
Also, you can change your constructor of Polygon class (which accepts int) as follows because you are not using the numPoints variable or else use an array with numPoints as the size instead of ArrayList.
public Polygon() {
p = new ArrayList<>();
}
You did not increment points in the addPoint(double x, double y) function.
Why not reuse the same method? and call the overloaded function
public boolean addPoint(Point2d point); instead of writing the same logic again and again.
public boolean addPoint(double x, double y) {
Point2d a = new Point2d(x,y);
return addPoint(a);
}

manipulation of classes in java

I'm getting confused about how to extract data from a custom class. The code groups Cartesian coordinates in a class called linesegment, with several instances of class CartesianCoordinate as its members. I am stuck trying to find the distance between two sets of cartesian coordinates.
How am I supposed to decode the linesegment class, into the cartesiancoordinate class, to then access the individual double values to print to screen from the main class?
Below are the three classes used within my program:
The main class:
public class lab3
{
public static void main(String [] args)
{
cartesiancoordinate one, two; //instantsiating one and two as type cartesiancoordiante
one = new cartesiancoordinate(5, 6); //putting the information for one and two into type cartesiancoordinate
two = new cartesiancoordinate(4.5, -6.5);
linesegment oneandtwo;
oneandtwo = new linesegment(one, two);
System.out.println(one.toString()); //dual X/Y statements using a toString method
System.out.println(two.toString());
System.out.println(oneandtwo.tostring());
System.out.println("X for one is: " + one.getx()); //individual X/Y statements using getter methods
System.out.println("Y for one is: " + one.gety());
System.out.println("X for two is: " + two.getx()); //individual X/Y statements using getter methods
System.out.println("Y for two is: " + two.gety());
double tester;
oneandtwo.test();
System.out.println("The test method returned the distance between the two cartesian coordinates to be: " + tester);
}
}
The cartesiancoordinate class:
class cartesiancoordinate
{
private double xposition;
private double yposition;
public cartesiancoordinate(double x, double y)
{
this.xposition = x;
this.yposition = y;
}
public double getx()
{
return this.xposition;
}
public double gety()
{
return this.yposition;
}
public String toString()
{
return "(" + this.xposition + " / " + this.yposition + ")";
}
}
The troublesome linesegment class:
class linesegment
{
private cartesiancoordinate startpoint, endpoint, s1, e1;
public cartesiancoordinate one, two;
public linesegment(cartesiancoordinate x, cartesiancoordinate y)
{
this.startpoint = x;
this.endpoint = y;
}
public cartesiancoordinate getstartpoint()
{
return this.startpoint;
}
public cartesiancoordinate getendpoint()
{
return this.endpoint;
}
public String tostring()
{
return ("The start point is " + this.startpoint + " and the end point is " + this.endpoint);
}
public double test()
{
double x1,x2,y1,y2;
cartesiancoordinate s1,e1;
getstartpoint() = s1;
getendpoint() = e1 ;
s1.getx() = x1;
s1.gety() = y1;
e1.getx() = x2;
e1.gety() = y2;
double tester;
tester = x1 + x2 + y1 + y2;
return tester;
}
}
Instead of:
double tester;
oneandtwo.test();
You want:
double tester = oneandtwo.test();
This is a problem.
getstartpoint() = s1;
getendpoint() = e1 ;
Your methods are return-ing values, so if you want to assign them to s1 and e1, then you can do that like so
s1 = getstartpoint();
e1 = getendpoint();
That won't fix the logic of your code, but it should at least compile.
Your linesegment class is broken:
class linesegment {
// a linesegment is nothing more than defined by a starting and ending point
private cartesiancoordinate startpoint, endpoint;
public linesegment(cartesiancoordinate x, cartesiancoordinate y) {
this.startpoint = x;
this.endpoint = y;
}
public cartesiancoordinate getstartpoint() {
return this.startpoint;
}
public cartesiancoordinate getendpoint() {
return this.endpoint;
}
public String toString() {
return ("The start point is " + this.startpoint + " and the end point is " + this.endpoint);
}
public double test()
{
double dx = endpoint.getx()-startpoint.getx();
double dy = endpoint.gety()-startpoint.gety();
return Math.sqrt(dx*dx+dy*dy);
}
}
Now in the main:
double tester = oneandtwo.test(); // get the distance
System.out.println("Distance is "+tester);
Please use standard naming conventions. Your classes must be spelled CartesianCoordinates, LineSegment, Lab3. Your variables: oneAndTwo, startPoint, endPoint...

Printing a 2d array of coordinates in java

I am trying to print the array that I have created in the Lab12 class using nested for loop and the getX() and getY() methods that I created in the MyPoint class. However my loop is just giving me the reference. how do i get the values to print
pt[0][0] = (0.5, 1.2)
pt[0][1] = (0.0, 3.14)
pt[0][2] = (15.0, 27.5)
pt[1][0] = (6.6, 7.7)
pt[1][1] = (1.2, 2.1)
pt[1][2] = (12.0, 127.0)
public class MyPoint {
private double x;
private double y;
public MyPoint(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
public class Lab12 {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyPoint [][]pointMatrix = {
{new MyPoint(0.5,1.2), new MyPoint(0.0,3.14), new MyPoint(15.0,27.5)},
{new MyPoint(6.6,7.7), new MyPoint(1.2,2.1), new MyPoint(12.0,127.0)}
};
for (int i=0; i<pointMatrix.length; i++) {
for (int j=0; j<pointMatrix[i].length; j++){
System.out.print(pointMatrix[i][j] + " ");
}
System.out.println();
}
}
The best option, as #Lashane mentioned, is to implement the toString() method:
public class MyPoint {
// ...
#Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
Inside your loop:
System.out.println("pt[" + i + "][" + j + "] = " + pointMatrix[i][j]);

Java seems to be ignoring my toString method

Ok, so I have made a toString() method for this Coordinate Class, but when I try to print a Coordinate using system.out.print(), it seems to ignore my method and just use the Object.toString() method, and just returns a memory address.
Here is my code for the toString method:
package spacetable;
public class Coordinate {
private int x;
private int y;
public Coordinate(){
x=0;
y=0;
}
public Coordinate(int x, int y){
this.x = x;
this.y = y;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public double distTo(Coordinate xy){
double run = xy.getX() - this.getX();
double rise = xy.getY() - this.getX();
double dist = sqrt(run*run + rise*rise);
return dist;
}
public double distTo(int x, int y){
double run = x - this.getX();
double rise = y - this.getX();
double dist = sqrt(run*run + rise*rise);
return dist;
}
#Override
public String toString(){
String Strx = Integer.toString(x);
String Stry = Integer.toString(y);
String result = "(" Strx + ", " + Stry + ")";
return result;
}
}
and my code that tries to print:
package spacetable;
public class CordinateTest {
public static void main(String[] args) {
Coordinate place = new Coordinate(2,3);
System.out.println(place);
}
}
And the output is:
spacetable.Coordinate#e53108
why is my toString() being ignored?
Your code works fine for me, take a look here
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static class Coordinate {
private int x = 3;
private int y = 5;
#Override
public String toString(){
String Strx = Integer.toString(x);
String Stry = Integer.toString(y);
String result = "(" + Strx + ", " + Stry + ")";
return result;
}
}
public static void main (String[] args) throws java.lang.Exception
{
Coordinate place = new Coordinate();
System.out.println(place);
}
}
are you sure you recompiled after you added the toString method. If you are using an IDE, please check that build automatically is set. If not build the code again
Also, can you paste the import command. just want to make sure you are importing your own Coordinate class and not a class of some third party jar
public class Coordinate {
private int x;
private int y;
public Coordinate(int x,int y)
{
this.x=x;
this.y=y;
}
public String toString()
{
String result = "("+ x + ", " + y + ")";
return result;
}
public static void main(String[] args) {
Coordinate place = new Coordinate(2,3);
System.out.println(place);
}
}

Categories