Hi
I have written such this code but it will return this exception .and I do not know why please help me thanks.
private void Scan(DoublyLinkedList dList) { // T(n) = O(n)
DNode p1 = dList.getFirst();
while (p1!=null) {
DNode p2 = p1.next;
System.out.println(p1.getElement().toString()+"lol");
if (p2.next!=null) {
DNode p3 = p2.next;
if(p3.getElement()!=null){
boolean b = Determinate.isPointRightSide(p1.getElement(), p2.getElement(),p3.getElement());
if (b == true) {
p1 = p1.next;
} else {
p1.next = p3;
p3.prev = p1;
dList.remove(p2);
p1 = p1.prev;
}
}
else break;
}else break;}
}
public static double determinate(Object get, Object get0, Object get1) {
double data[][] = new double[3][2];
data[0][0] = ((Point) get).getX();
data[0][1] = ((Point) get).getY();
data[1][0] = ((Point) get0).getX();
data[1][1] = ((Point) get0).getY();
**data[2][0] = ((Point) get1).getX();**
data[2][1] = ((Point) get1).getY();
return ((data[0][0] * (data[1][1] - data[2][1])) - (data[1][0] * (data[0][1] - data[2][1])) + (data[2][0] * (data[0][1] - data[1][1])));
}
exception:
run:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at ConvexHull.Determinate.determinate(Determinate.java:55)
at ConvexHull.Determinate.isPointRightSide(Determinate.java:15)
at ConvexHull.GrahamVersion.Scan(GrahamVersion.java:104)
at ConvexHull.GrahamVersion.grahamScan(GrahamVersion.java:83)
at ConvexHull.GrahamVersion.<init>(GrahamVersion.java:25)
at UI.MainFrame.grahamButtonActionPerformed(MainFrame.java:221)
this will show that "p3" is null! but I have check "p3" why it returns "null" again?
I use strong for showing those lines that throws exception.
EDIT: Ihave edited my post but it will throw this exception for "p1"
One thing that looks wrong is:
if (!p3.equals(null))
This will generally always be true (if p3 != null) or throw a NullPointerException (if p3 == null)
The correct way to test whether p3 is not null is:
if (p3 != null)
Although that may not be why you're getting your NullPointerException
If the NullPointerException occurs on the line you highlight, it must be because get1 is null. This is passed in as p3.getElement(), so find out whether that could be null.
In theory, if data[2] was null then data[2][0] would throw a NullPointerException but since you initialize data then that won't be the problem in this case.
Also, is there some reason that your parameters for determinate() are Object instead of Point? If this is your actual code and not some simplified test-case, then the parameters should all be Point since that's what they must be.
Edit:
I see you've changed your original code to add some of the suggestions on this page.
But I still see some problems:
while (p1!=null) {
DNode p2 = p1.next;
if (p2.next!=null) {
// ^^^^^^^ If p2 is null, then this will throw NullPointerException
DNode p3 = p2.next;
if(p3.getElement()!=null){
// ^^^^^^^^^^^^^^^ If p3 is null, then this will throw NullPointerException
boolean b = Determinate.isPointRightSide(p1.getElement(), p2.getElement(),p3.getElement());
// ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ if one of these returns null then isPointRightSide() will throw a NullPointerException
I'm pretty sure you got the wrong line, because this:
!p3.equals(null)
will not work - that line (or those involving p1 or p2) is throwing the Exception. You cannot invoke any method on a null, including equals(). Use this instead for all your null checks:
p3 != null
Related
I am new to programming. My question might be dumb. (***If there is no value for others, I will delete this question later)
See these two functions here:
1.
StringBuilder sb = new StringBuilder();
private String preorder(TreeNode root) {
if(root == null){
sb.append("null,");
}
sb.append(root.val);
sb.append(",");
String l = preorder(root.left);
String r = preorder(root.right);
return sb.toString();
}
2.
StringBuilder sb = new StringBuilder();
private String preorder(TreeNode root) {
if(root == null){
sb.append("null,");
}
else{
sb.append(root.val);
sb.append(",");
String l = preorder(root.left);
String r = preorder(root.right);
}
return sb.toString();
}
If I call these two functions in the main function.
The 1st one will threw
java.lang.NullPointerException error.
I understand that when java.lang.NullPointerException occurs:
1. when declare a variable but did not create an object
2. assign to the variable before trying to use the contents of the variable
(update on this part:
After IF condition, regardless there is a else or no, it will execute the rest of body, thanks for everyone's help)
(Stale. Ignore the rest of part: )
After
if(root == null)
the rest should be
root != null
Correct me if I am wrong.
Answer
You are missing an else case.
private String preorder(TreeNode root) {
if(root == null){
sb.append("null,");
}else{
// ...
}
The code below your if condition will still execute if you do not add an else
or return.
It will throw an NPE because after your condition you
try to access root with:
sb.append(root.val);
Further Explanation
You need to read it like a sentence.
if(thisIsTrue){
// Then do that
}else{
// Do that
}
Where "thisIsTrue" is your condition. i.e root != null.
If you try to access a member of root with root.val,
where you try to acces val, then root must not be null,
or an NullPointerException will be thrown.
Metaphorically speaking..imagine you have a bag of apples.
What you are trying to do, is to grap an apple, but you have no bag.
I think this is clear.
If you omit the else clause, then it will execute like the following:
if(thisIsTrue){
// It will do that, if condition is true
}
// It will ALWAYS execute this, even if condition is false
With if/else
You open two branches. Only one of them gets executed.
With if, but no else
You have one conditional branch that gets execute if the
condition is true, but the code underneath will be execute always afterwards.
Hello fellow coders,
I am writing a mod for Minecraft in 1.8 and have come across a pesky NullPointerException with my throwable. In the code below, the EntityThrowable uses an outer class to get the results of what will happen when thrown and the BlockPos passed is from the getBlockPos() method. This position is passed to the outer class where it transformed into x, y and z coords. However, whenever I throw the throwable, it throws an exception for these coordinates.
The difference between this question and the question of what is a NullPointerException is that the return value of what I am getting from the mov.getBlockPos() (from a MovingObjectPosition) is unknown. The MovingObjectPosition assigns the coords of the BlockPos from a random class and the coder of the Throwable gets the results. I am using the results for the outer class. These results in the ints cause the game to crash from unknown coords. If you have any idea of how to get the end pos of the throwable, that would be appreciated.
Here's the code:
Throwable:
#Override
protected void onImpact(MovingObjectPosition mov) {
LuckyPotionItems lpi = new LuckyPotionItems();
EntityPlayer player = this.getThrower() instanceof EntityPlayer ? (EntityPlayer) this.getThrower() : null;
if(!worldObj.isRemote)
lpi.chooseUnluckyDrink(worldObj, player, mov.getBlockPos());
this.setDead();
}
Outer Class:
public void chooseUnluckyDrink(World w, EntityPlayer p, BlockPos pos){
Random r = w.rand;
int number = r.nextInt(13);
int x = pos.getX();
int y = pos.getY();
int z = pos.getZ();
System.out.println("Unlucky Number = " + number);
Thanks for any help.
It sounds like the problem could be solved by checking if the BlockPos and the EntityPlayer are not null. If they aren't null, then run the method. If they are null, simply prevent the method from being ran.
#Override
protected void onImpact(MovingObjectPosition mov) {
LuckyPotionItems lpi = new LuckyPotionItems();
EntityPlayer player = this.getThrower() instanceof EntityPlayer ? (EntityPlayer) this.getThrower() : null;
if(mov.getBlockPos() != null && player != null) {
if(!worldObj.isRemote)
lpi.chooseUnluckyDrink(worldObj, player, mov.getBlockPos());
this.setDead();
}
}
number = (number == null) ? "" : number;
System.out.println("Unlucky Number = " + number);
int x = (pos.getX() == null ) ? 0 : pos.getX();
you are getting a null value for the number which means there is no output in r.nextInt(13); you need to fix that. Im using a conditional statement to check the value of number if its null then it will assign a value for number which can then be printed. try with my example this would help you.
Today I got a NullPointerException at a point where it actually can't occur.
Exception in thread "Timer-9" java.lang.NullPointerException
at packagename.censored.Bot.changeServergroups(Bot.java:1363)
at packagename.censored.Bot.xpTask(Bot.java:1239)
at packagename.censored.Bot.access$7(Bot.java:1187)
at packagename.censored.Bot$9.run(Bot.java:729)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
This is the relevant part of the code:
public void changeServergroups(int cldbid, ArrayList<Integer> addList, ArrayList<Integer> removeList) {
// If there are groups to add AND delete, remove them from the lists
if (addList != null && removeList != null) {
ArrayList<Integer> temp = new ArrayList<Integer>(addList);
for (int s : temp) { // THIS IS LINE 1363
if (removeList.contains(s)) {
addList.remove((Integer) s);
removeList.remove((Integer) s);
}
}
}
// some more code, to do the actual group changes
}
How is it possible to get the NullPointerException there? I check to make sure that addList is not null before creating a new temporary ArrayList from it. Can someone tell me how this could possibly return in a NullPointerException?
The only possibility is that your list temp contains null. The null Integer is then unboxed to an int and that throws a NPE.
You can solve the NPE by using for (Integer s : temp) if having a null value is acceptable.
Findbugs is showing NP_NULL_ON_SOME_PATH for a line.
It says that there is a branch of statement that, if executed, guarantees that a null value will be dereferenced, which would generate a NullPointerException when the code is executed.
Of course, the problem might be that the branch or statement is infeasible and that the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs.
Here is the code:
public int compare(Object o1, Object o2)
{
....
String sTypeName1 = row1.getFieldValue(OBJECT_TYPE_FIELD_NAME);
String sTypeName2 = row2.getFieldValue(OBJECT_TYPE_FIELD_NAME);
if (sTypeName1!= null && sTypeName1.indexOf("~") != -1)
{
sTypeName1 = m_oc.getString(sTypeName1);
}
if (sTypeName2!= null && sTypeName2.indexOf("~") != -1)
{
sTypeName2 = m_oc.getString(sTypeName2);
}
int cf = sTypeName1.compareTo(sTypeName2);
if (cf == 0)
{
cf = o1.toString().compareTo(o2.toString());
}
return cf;
}
It is showing 2 errors of same kind for the code:
int cf = sTypeName1.compareTo(sTypeName2);
Here it says that there is a possible null pointer dereference from the value loaded from sTypeName1.
So I had to put a null check before this code like:
if(sTypeName1 != null && sTypeName2 != null)
{
int cf = sTypeName1.compareTo(sTypeName2);
}
but the issue is not resolved. :(
Could anyone suggest a solution and also what is wrong with my approach?
Thanks a lot for going through my question :)
For me the issue is resolved. This code does not produce a bug report:
String sTypeName1 = row1.getFieldValue("qqq");
String sTypeName2 = row2.getFieldValue("www");
if (sTypeName1 != null && sTypeName1.indexOf("~") != -1) {
sTypeName1 = m_oc.getString(sTypeName1);
}
if (sTypeName2 != null && sTypeName2.indexOf("~") != -1) {
sTypeName2 = m_oc.getString(sTypeName2);
}
int cf = 0;
if (sTypeName1 != null && sTypeName2 != null) {
cf = sTypeName1.compareTo(sTypeName2);
}
if (cf == 0) {
cf = o1.toString().compareTo(o2.toString());
}
return cf;
Probably you did not recompile your code or did not perform the FindBugs analysis again.
From my experience this can be caused by situations like this:
Situation 1 - Findbugs will complain if you only set b under some conditions, such as if a is not null, then later reference b. If a could really be null, you need to handle what to do if b is null too as a result. If a is never null, remove the null check. Also, for me it identified the line where b was defined as the first problematic line, rather than when b.doSomething() is called.
if (a != null) {
b = a.getB();
}
b.doSomething();
Situation 2 - You nullcheck in one place, but not another. Nullcheck everywhere, or nowhere
if (x != null) {
x.doSomething1();
}
x.doSomething2();
public void createGraph () {
int oldFrom = -1;
int oldTo = -1;
for(int i = 0; i < edges.size(); i++) {
EdgeI e = edges.get(i);
int from = e.from;
int to = e.to;
VertexI v = vertices.get(from);
if (from == oldFrom && to == oldTo){
vertexWeight wic = v.neighbors.get(v.neighbors.size() - 1);
wic.w++;
}
else {
v.neighbors.add(new vertexWeight (to, 1));
oldFrom = from;
oldTo = to;
}
}
}
neighbors is a public List from VertexI class. w is a public integer from vertexWeight class. edges is a list located in my main class. I keep getting a null pointer exception for this line of code:
v.neighbors.add(new vertexWeight (to, 1));
Tried working on it for around 15 minutes and I didn't get it to work. What am I messing up on?
java.lang.NullPointerException
at tester.createGraph(tester.java:60)
at tester.main(tester.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Short answer
Initialize v.neighbors with new ArrayList() in vertices.get().
Long answer
Your question omitted a crucial information: How you initialized neighbors. Why is this important?
See: What is a NullPointerException, and how do I fix it?
In your case I guessed that either v or neighbors is null during the run of the program. For example vertices.get(from) could return null and v.neighbors won't work. Or neighbors is null, and v.neighbors.add() won't work.
And voilĂ . You admitted that you set neighbors to null when initializing VertexI.
The solution is: Initialize with new ArrayList() instead of null.
If that would not have been possible or you cannot avoid null pointers for some other reason, you can do null pointer checks like this:
if (v != null && v.neighbors != null) {
v.neighbors.add(new vertexWeight (to, 1));
}
This means, don't add vertices if v or neighbors are null.
But this is complicated and error-prone. It is easier to avoid null pointers as much as possible. Some would say, avoid them at all costs! Throw an exception instead or return an "empty" object like new ArrayList().