java.lang.NullPointerException when using methods from multiple classes [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm new to programming java and I'm attempting to find out why my code keeps giving me the error java.lang.NullPointerException. It's supposed to take 6 points, and create 2 triangles.
MAIN CLASS
public class Themain{
public static void main (String[] args){
Point pointone = new Point(1,2);
Point pointtwo = new Point(3,4);
Point pointthree = new Point(0,5);
Point josh = new Point(1,2);
Point abby = new Point(3,4);
Point trevor = new Point(0,6);
Triangle2D triangleone = new Triangle2D();
Triangle2D triangletwo = new Triangle2D();
triangleone.setPoint1(pointone);
triangleone.setPoint2(pointtwo);
triangleone.setPoint3(pointthree);
triangletwo.setPoint1(josh);
triangletwo.setPoint2(abby);
triangletwo.setPoint3(trevor);
}
}
TRIANGLE CLASS
public class Triangle2D{
Point p1;
Point p2;
Point p3;
//no args constructor
public Triangle2D(){
}
//set point one
public void setPoint1(Point p){
p1.setXPos(p.getXPos());
p1.setYPos(p.getYPos());
}
//set point two
public void setPoint2(Point p){
p2.setXPos(p.getXPos());
p2.setYPos(p.getYPos());
}
//set point three
public void setPoint3(Point p){
p3.setXPos(p.getXPos());
p3.setYPos(p.getYPos());
}
//get point one
public Point getPoint1(){
return(p1);
}
}
POINT CLASS
public class Point{
int x;
int y;
//args constructor
public Point(int x, int y){
this.x = x;
this.y = y;
}
//get the x-coordiante
public int getXPos(){
return x;
}
//set the x-coordinate
public void setXPos(int x){
this.x = x;
}
//get the y-coordinate
public int getYPos(){
return y;
}
//set the y-coordinate
public void setYPos(int y){
this.y = y;
}
//is equals method
public boolean isEquals(Point t){
return(this.x == t.x && this.y == t.y);
}
}
I'm not sure why it's giving my the null error. The real code is much longer than this but I have take the section that was causing the error and I put it into this file. I'm mostly writing this because stack overflow says there is too much code. If someone could help me understand why this error appears it would be greatly appreciated.

The p1, p2, p3 objects are null, you did not initialize them.
2 solutions :
Initialize them
public Triangle2D(){
p1 = new Point();
p2 = new Point();
p3 = new Point();
}
require to add a 0-arg constructor for Point : public Point(){}
Assign the value when use the setter
public void setPoint1(Point p){
p1 = p;
}

Point p1; this is null
change to this pattern of code
public void setPoint1(Point p){
p1 = p;
}
or alternatively you could construct the points in the constructor
public Triangle2D(){
p1 = new Point (-1, -1); // or even better create a zero arg constructor
}

Related

Adding objects to an array list - "Cannot invoke xxx.add because yyy is null" [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I have a class of objects:
public class SubObjects {
int depth;
public SubObjects(int d) {
this.depth = d;
}
}
And then another class of objects:
import java.util.ArrayList;
public class Objects {
private int height;
private int width;
ArrayList<SubObjects> liste;
public Objects(int h, int w) {
this.height = h;
this.width = w;
}
}
The idea here is that each object should be able to hold a height value, a width value and a list of SubObjects.
E.g. = 2,4,[SubObject1, SubObject2]
The following being the main class:
import java.util.*;
public class Tryout {
public static void main(String[] args) {
SubObjects S1 = new SubObjects(7);
SubObjects S2 = new SubObjects(9);
Objects O1 = new Objects(2,4);
O1.liste.add(S1);
O1.liste.add(S2);
System.out.println(O1);
}
}
First I create two SubObjects.
Then I create an Object with the ints 2 and 4.
Where everything goes astray is the next line:
O1.liste.add(S1);
The error code given:
Cannot invoke "java.util.ArrayList.add(Object)" because "O1.liste" is null
Now I get that the array list is null, I have not added anything yet of course, but why can't I add anything to it?
liste is not initilized. In other words, it isn't an ArrayList - it's a null reference. Since there's no object there, you can't call any methods on it.
To solve the issue, you could initialize liste in the constructor:
public Objects(int h, int w) {
this.height = h;
this.width = w;
this.liste = new ArrayList<>();
}
liste was never initialized. Either initialize as below or in the constructor.
public class Objects {
private int height;
private int width;
ArrayList<SubObjects> liste = new ArrayList<>(); // <===add this
public Objects(int h, int w) {
this.height = h;
this.width = w;
}
}

Why did I get a NullPointerException when I did not use setter in main method?

I have a question about using getters and setters, and null pointer exception.
I basically called a simple function, getSlope() on a Line object, l, in my program which has Line and Point classes.
When I called l.getSlope() with
Point p1 = new Point(0.0, 3.0);
Point p2 = new Point(5.0, 5.0);
Line l = new Line(p1, p2);, it gave me a null pointer exception.
However, when I called l.getSlope() with
Line l = new Line();
l.setP1(0.0, 3.0);
l.setP2(5.0, 5.0);, it DID NOT give me a null pointer exception.
Why is this? Thank you for your help. The code for Point and Line classes are posted below for your information.
Point:
public class Point {
private double x;
private double y;
public Point() {
this.x = 0.0;
this.y = 0.0;
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public String toString() {
return "(" + this.x + ", " + this.y + ")";
}
public static void main(String[] args) {
Point p = new Point(1.5, 3);
System.out.println(p.toString());
}
}
Line:
public class Line {
private Point p1;
private Point p2;
public Line() {
p1 = new Point(0,0);
p2 = new Point(0,0);
}
public Line(Point p1, Point p2) {
p1 = new Point(p1.getX(), p1.getY());
p2 = new Point(p2.getX(), p2.getY());
}
public Point getP1() {
return this.p1;
}
public Point getP2() {
return this.p2;
}
public void setP1(double x, double y) {
this.p1 = new Point (x, y);
}
public void setP2(double x, double y) {
this.p2 = new Point(x, y);
}
public double getSlope() {
return ((p2.getY() - p1.getY()) / (p2.getX() - p1.getX()));
}
public static void main(String[] args) {
// Point p1 = new Point(0.0, 3.0);
// Point p2 = new Point(5.0, 5.0);
// Line l = new Line(p1, p2);
// System.out.println(l.getSlope()); // These 4 lines produced errors
Line l = new Line();
l.setP1(0.0, 3.0);
l.setP2(5.0, 5.0);
System.out.println(l.getSlope()); // These 4 lines worked!
}
}
I'll put this in an actual answer, so I have more room to work with.
The issue here is your Line constructor. You're running into something called "variable shadowing".
public Line(Point p1, Point p2) {
p1 = new Point(p1.getX(), p1.getY());
p2 = new Point(p2.getX(), p2.getY());
}
You pass variables into that constructor named p1 and p2:
public Line(Point p1, Point p2) // Here are p1 and p2 being passed into the constructor
Now you also have a p1 and p2 defined at the class level, like so:
private Point p1;
private Point p2;
What you want to do is create new Points based on the p1 and p2 being passed into the constructor, and store those new Points in these class-level variables.
But since the constructor has local variables with the same name as the class-level variables, the local variables take precedence, and "hide" the class-level variables. This is known as "shadowing".
So in the constructor, when you want to access those class-level variables, you have to reference them as this.p1 and this.p2, since p1 and p2 refer to the constructor parameters.
public Line(Point p1, Point p2) {
p1; // <-- This is the p1 being passed into the constructor
this.p1; // <-- This is the class-level variable with the same name
}
When you use this. to get to the correct variables, the code should look like this:
public Line(Point p1, Point p2) {
this.p1 = new Point(p1.getX(), p1.getY());
this.p2 = new Point(p2.getX(), p2.getY());
}
A quick visual reference:
private Point p1; // <------------------+
private Point p2; // |
// |
// +--------------- + |
// | | |
// v | |
public Line(Point p1, Point p2) {
// | |
p1; // <--these are the same---+ |
this.p1; // <--these are the same---+
}

Print List in Java

I'm newbie in Java. I'm not sure why line my2.print_list(); is printing only object my2. I want to print every time whole list of objects. I'm adding every object to list in constructor. I'm 90% sure that for loop in function print_list is good. The compiler shows no problems. I'll appreciate all help.
public class Main {
public static void main(String[] args) {
// write your code here
rectangle my = new rectangle(5);
rectangle my1 = new rectangle(3,6);
rectangle my2 = new rectangle(10,7);
System.out.println( my2.getCounter());
my2.print_list(); ////////////////////<- described line
}
}
/// my class rectangle
import java.util.ArrayList;
import java.util.List;
public class rectangle {
public static int counter =0;
public int x;
public int y;
public List<rectangle> List = new ArrayList<rectangle>();
public rectangle(int x, int y) {
this.x = x;
this.y = y;
System.out.println("Rec");
List.add(this);
counter++;
}
public rectangle(int x) {
this.x = x;
this.y = x;
System.out.println("Sqr");
List.add(this);
counter++;
}
#Override
public String toString() {
return "x->"+x+" y->"+y+" Field: "+(x*y);
}
public void print_list()
{
for(rectangle x : List)
{
System.out.println(x);
}
}
Every instance of your class has its' own instance of List. Make it static if it should be shared (which is the only way your List will be populated). Also, please rename the variable List (it looks exactly like the interface java.util.List). Also, there's no reason to make it public.
private static List<rectangle> myList = new ArrayList<rectangle>();
And then change print_list like
public void printList()
{
for(rectangle x : myList)
{
System.out.println(x);
}
}
Also, the class name should be Rectangle (to follow Java naming conventions).
Change
public List<rectangle> List = new ArrayList<rectangle>();
to
public static List<rectangle> List = new ArrayList<rectangle>();
So there's only one instance of List.

Java math error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm working on a lab for programming principles II, and I have a class that makes a point, with methods for setting the point, and calculating the distance between other points. Calculating the distance worked fine when testing it with a runner for just the class, but when I make other classes that use it as an object, I'm getting an error with the distance formula.
import java.lang.Math;
public class MyPoint {
private double x;
private double y;
public MyPoint(double dubx, double duby)
{
x=dubx;
y=duby;
}
public void setX(double dub) {
x = dub;
}
public void setY(double dub) {
y = dub;
}
public double getX() {
return x;
}
public double getY()
{
return y;
}
public double distance (MyPoint otherPoint)
{
return Math.sqrt(Math.pow((otherPoint.getX()-getX()),2)+(Math.pow((otherPoint.getY()-getY()),2)));
}
public MyPoint midpoint(MyPoint otherPoint)
{
MyPoint point = new MyPoint((otherPoint.getX()+getX()/2),(otherPoint.getY()+getY())/2);
return point;
}
}
That's the class I'm getting the error on. The distance part is getting a null pointer exception.
Here's what I'm passing in:
import java.lang.Math;
public class MyTriangle
{
private MyPoint v1;
private MyPoint v2;
private MyPoint v3;
public MyPoint getPoint1()
{
return v1;
}
public MyPoint getPoint2()
{
return v2;
}
public MyPoint getPoint3()
{
return v3;
}
public void setPoint1(double x, double y)
{
v1= new MyPoint(x,y);
}
public void setPoint2(double x, double y)
{
v2 = new MyPoint(x,y);
}
public void setPoint3(double x, double y)
{
v2= new MyPoint(x,y);
}
public double getArea()
{
double a= v2.distance(v3);
double b= v1.distance(v3);
double c= v1.distance(v2);
double s= (a+b+c)/2;
return Math.sqrt(s*(s-a)*(s-b)*(s-c));
}
}
public class TestMyTriangle
{
public static void main(String [] args)
{
MyTriangle tr1 = new MyTriangle();
tr1.setPoint1(17,17);
tr1.setPoint2(5,30);
tr1.setPoint3(5,17);
System.out.println("Area:\t"+tr1.getArea());
}
}
And the error:
Exception in thread "main" java.lang.NullPointerException
at MyPoint.distance(MyPoint.java:34)
at MyTriangle.getArea(MyTriangle.java:37)
at TestMyTriangle.main(TestMyTriangle.java:9)
I can't seem to figure it out. Please help.
You get the Nullpointer because v3 is null:
fix with:
public void setPoint3(double x, double y)
{
v3= new MyPoint(x,y); // instead of v2
}
Another tipp: to calculate a square dont use Math.pow(x,2).
Altough it works.
The code is cleaner and faster if you use
x*x instead Math.pow(x,2);

Making a Class Immutable

I am learning about immutable Objects. I have to make following class immutable. Did i do it right?
import java.awt.Point;
public class MyImmutablePoint {
Point point;
public MyImmutablePoint(Point point) {
super();
this.point = point;
}
public MyImmutablePoint() {
this (new Point (0,0));
}
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point
}
}
"Immutable" Class:
public final class MyImmutablePoint {
private final Point point;
public MyImmutablePoint(Point point) {
this.point = point;
}
public MyImmutablePoint() {
this (new Point (0,0));
}
public Point getPoint() {
return point;
}
}
Iam not sure about the toString method though.
and maybe returning an object like Point can be modified as well like an array but not sure
No
final Point p = new Point(0,0);
final ImmutablePoint ip = new ImmutablePoint(p);
Two examples:
//change the original Point passed in
p.x = 10
//use the getter and change the Point
ip.getPoint().x = 10
So, first you need to create a defensive copy of the Point taken in the constructor:
public MyImmutablePoint(Point point) {
this.point = new Point(point);
}
Then you need to create a defensive copy of the Point returned from the getter:
public Point getPoint() {
return new Point(point);
}
This all leads me to suggest that it would probably be better not to expose the internal point at all:
public final class MyImmutablePoint {
private final Point point;
public MyImmutablePoint(Point point) {
this.point = new Point(point);
}
public MyImmutablePoint() {
this.point = new Point (0,0);
}
public int getX() {
return point.x;
}
public int getY() {
return point.y;
}
}
Further format your code and order your members.
No it is not immutable. Point can still be modified by the creator of MyImmutablePoint. Ex:
Point point = new Point(1, 1);
MyImmutablePoint immutablePoint = new MyImmutablePoint(point);
point.setLocation(0, 0);

Categories

Resources