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 "ja开发者_高级运维va.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! :)
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;
}
}
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.
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.
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;
}
精彩评论