Reputation: 8818
public boolean addPoint(Point p){
points.add(p);
extremes();
return points.add(p);
}
Alright so when I run this code the main class calls addPoint and passes it a Point, however when it gets to the line "points.add(p);" it gives me a "java.lang.NullPointerException" error. FYI: "points" is an arrayList.
Also on a side note, am I using the "return points.add(p);" right to return a boolean value? And on another side note I don't seem to be calling "extremes();" right, as I get an Unreachable code error.
Thanks for all the help! :)
Upvotes: 2
Views: 8618
Reputation: 66156
You probably forgot to initialize your ArrayList (i.e. points
). Just do something like this:
class YourClass {
private final List<Point> points = new ArrayList<Point>();
public boolean addPoint (Point p) {
boolean result = points.add(p);
extremes();
return result;
}
}
Upvotes: 10
Reputation: 120178
You get an unreachable code error because your call to extremes() is AFTER the return. Your method will always return and NEVER get there.
I think what you want is
public boolean addPoint (Point p) {
boolean didAdd = points.add(p);
extremes();
return didAdd;
}
no need to call add twice.
Upvotes: 2
Reputation: 11454
Your NullPointerException is because points is null - did you new it in your constructor?
Unless it's your intent to stick the point in your list twice, you don't want to call points.add(p) twice. What you probably want to do is:
public boolean addPoint (Point p) {
boolean result = points.add(p);
extremes();
return result;
}
Upvotes: 1
Reputation: 838086
You are correct that extremes() will never get called. Either reorder the last two lines, or if the order is important then do this:
public boolean addPoint(Point p){
boolean result = points.add(p);
extremes();
return result;
}
I'd also recommend that you format your code neatly so that it is easier to read, and use more descriptive names than for example extremes
. It is not clear whether this method is searching for the extremes and returning them or if you are calling it for some side-effect. If it is the former then it is strange that you are not actually using the return value - perhaps this is another error in your code.
Upvotes: 2