NullPointerException with a ticking entity Minecraft modding 1.8 - java

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.

Related

Is there a way that i can make my object never null?

I was given a task and I'm not sure how to get it to work. All the test cases must pass.
Assertions.assertDoesNotThrow(() -> p3.equals(null));
Assertions.assertFalse(p3.equals(null), "equals to null should return false");
I figured out the first one, the one that is tricking me is the Assertions.assertfalse(p3.equals(null)).
I created the object p3 from Point as such:
Point p3 = new Point(x+1, y-1);
In my Point class I have an equals method which I override as such:
#Override
public boolean equals(Object obj) {
Point p = (Point) obj;
try {
if (x != p.x) {
return false;
}
if (y != p.y) {
return false;
}
} catch (NullPointerException e) {
System.err.println("null");
}
return true;
}
I used this to pass other tests not mentioned.
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int x() {
return x;
}
public int y() {
return y;
}
Where x and y are random integers between 0-30.
When I run the test, it always returns p3 equal to null which is confusing me. I know it is something to do with checking if the object passed through is of same type (Point) & downcasting, but I am not sure.
If you look at the signature of the equals method you are implementing you'll see it takes an argument of type Object. That means the thing passed in can be any reference type. It can be null. Currently your equals method blindly casts whatever it gets to a Point, so if it gets anything other than a Point then an exception gets thrown. Then later, if the thing passed in is null, referencing an instance member (like p.x) will cause a NullPointerException.
There are at least four tests you need to write for your equals method:
Pass in another Point with the same x and y values,
Pass in a Point with different x and y values.
Pass in some object with a totally different type, like String or Integer.
Pass in null.
These need to be in different test methods, so that they can fail independently of each other. Cramming them into the same test means that when one assertion fails, the ones after it don't run; fixing tests turns into a whack-a-mole situation where you fixed one problem but now another one pops up.
You can use instanceof to check that what you are getting is the right type and is non-null. Since your current code catches a NPE, it lets execution continue from the catch block to the line with return true; , which isn't what you want.
So start your equals method with something like
if (!(object instanceof Point)) {
return false;
}
before you cast. Once you know the object is a non-null Point then you can continue with
Point p = (Point)object;
return x == p.x && y == p.y;
Since && short-circuits this doesn't do any more work than the posted code, they both stop checking if the first check evaluates to false.

java null manual exception handling

I have this static method of the class Plane which returns an object from some int id:
private static ArrayList<Plane>Planes = new ArrayList<Plane>();
public static Plane getPlane(int id)
{
Plane p = null;
int i=0;
while(i<=Planes.size())
{
if(Planes.get(i).getid()==id)
{
p = Planes.get(i);
break;
}
i++;
}`
return p;
}
And I have this code which I want to manually throw an exception when the Plane object is null and print Plane doesnt exist!:
try
{
Plane planetofly = Plane.getPlane(pid);
if(planetofly==null)
{
throw new Exception("Plane doesnt exist!");
}
this.planetofly = planetofly;
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
but instead of getting "Plane doesnt exist at the output" when the plane with that id doesnt exist i get output the message from the IndexOutofBounds Exception.What am I doing wrong?
Index out of bounds means that you are trying to access an index in your array which does not exist.
This line is the problem.
while(i<=Planes.size())
The index starts at zero and ends at Size - 1, so you have to check for less than, not less than or equal to. Like this:
while(i < Planes.size())

Null pointer Exception, only when i try the type in array form [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am new to java
This is my first real project (card game: Blackjack)
I made a test class and was told to use print-lines to try and pinpoint my problem, however I cannot comprehend why the null exception keeps showing up. I don't have anything set to null, and my array has been initialized using the "new". I can also post the IO class, however i'm fairly certain that the issue is not within that.
public static void main(String[] args) {
// Initializing just a single player
Player x = new Player();
// Quick test to make sure it reads the initial value of 0
System.out.println(x.getMoney());
// Testing user input using an IO class given
System.out.println("How much would you guys like to play with?(Bet money)");
double y = IO.readDouble();
x.addMoney(y);
System.out.println(x.getMoney());
// Successfully prints out the value y
Player[] total = new Player[4];
total[1].addMoney(y);
System.out.println(total[1].getMoney());
// returns the null pointer exception error
}
Here is my Player class
package Blackjack;
public class Player {
private Hand hand = new Hand();
private double currentMoney = 0;
private double bet = 0;
public void takeCard(Card h) {
hand.addCardToHand(h);
}
public double getBet() {
return bet;
}
public double getMoney() {
return currentMoney;
}
public void betMoney(double k) {
currentMoney = -k;
bet = +k;
}
public void addMoney(double k) {
currentMoney = currentMoney + k;
}
public void resetBet() {
bet = 0;
}
I can see maybe the problem being within my initialization of hand, however I the fact that I don't ask to return anything from the hand portion of the code leads me to believe that's not where the issue lies.
Player[] total = new Player[4];
total[1].addMoney(y);
when you initialize an object array, it is "filled" with null references. So in this case, total[1] will return null, unless you assign a Player instance to index 1: total[1] = new Player();

checking and setting variable, efficiently

I am new to programming and have a simple question: is there a "better" or more efficient way of doing this...
if (x != 0) {
y = x;
}
or
if (getMethod() != null) {
value = getMethod();
}
I'm new to programming and above code (esp the 2nd one) seems inefficient.
Thanks in advance.
You second example can suffer from a "Time of check, to time of use" weakness. If the first invocation of getMethod() returns non-null, it is possible that your second invocation will return null. A better way to do it would be:
value = getMethod();
if(NULL != value)
{
/* use value as planned */
}
else
{
/* handle a null value, probably an error */
}
if interested, you can read more about TOCTTOU weaknesses here.
For your first example, I don't really see a better way of doing this.
N.B. This answer is from the perspective of a C programmer (seeing as how C was one of your tags).
Hope this helps
- T.
You can make it shorter
if ( x ) y = x;
is the same as
if (x != 0) {
y = x;
}
And
if ( getMethod() ) value = getMethod();
is the same as
if (getMethod() != null) {
value = getMethod();
}
First code snippet:
In C any non-zero value is treated as true and 0 treated as false. So, for the first example, you can rewrite it as:
if (x) {
y = x; // this line will be executed if x not equal to zero
}
Second code snippet:
You called getMethod() twice which is not efficient. As per your code, you are assigning the return value of getMethod() into value if getMethod() returns anything but NULL. So you can use a temporary variable to check the return value of getMethod(), like following:
temp = getMethod();
if (temp != null) {
value = temp;
}
That will reduce calling same method twice.

Java NullPointerException - Short Program

I'm new in programming in Java and I do not understand what's going on in my code.
It tells me:
Exception in thread "main" java.lang.NullPointerException
at Main.Country.addMine(Country.java:37)
at Main.Main.main(Main.java:21)
Java Result: 1
My main.java is simple:
Continent Europe = new Continent("Europe");
Country asd = new Country("asd", Europe);
Mine mine = new Mine(100,100,100,100);
System.out.println(mine == null);
asd.addMine(mine); //dies here
this is addMine method:
public void addMine(Mine mine) {
System.out.println(mine == null);
this.mines.add(mine); //dies here
this.iron += mine.iron;
this.gold += mine.gold;
this.stone += mine.stone;
this.wood += mine.wood;
System.out.println("Mine has been successfully added to the country with the given values."
);
and Mine.java is:
public class Mine implements Building { //Building is an empty interface :)
protected int iron;
protected int gold;
protected int stone;
protected int wood;
public Mine(int iron, int gold, int stone, int wood) {
this.iron += iron;
this.gold += gold;
this.stone += stone;
this.wood += wood;
}
}
As You can see I wrote 2 println-s and both of them were false, so the object exists! I don't understand why it shows NullPointerException :(
If this is failing:
this.mines.add(mine); //dies here
... then I suspect mines is a null reference. You haven't shown any declaration for it or initialization - but that should be your first port of call. Chances are it's just a case of changing:
private List<Mine> mines;
to
private List<Mine> mines = new ArrayList<Mine>();
or something similar.
Yes, mine could be not null but what about mines? Which I guess it's a ArrayList<Mine> or something like that, did you inizialize it as mines = new ArrayList<Mine>()? (or whichever collection it is)
Null pointer exception is thrown when you invoke method on reference that is null.
this.mines.add(mine); //dies here
this.mines reference is obviously equal to null.
Also try to make your reference variables names start with lowercase letters.
Continent Europe = new Continent("Europe");
->
Continent europe = new Continent("Europe");
Names with starting uppercase letters are 'reserved' for classes.
It's considered a good style in Java.
You code fails in the
this.mines.add(mine);
at County class.
In order to bypass the error you should create a local variable inside the County class(in case you dont have it) which will be
private List<Mine> mines;
and you will initialise it by adding the following
mines=new LinkedList<Mine>();
The above thing can be written in one line of code but that is up to you.
private List<Mine> mines=new LinkedList<Mine>();
You can use any other implementation of List.

Categories

Resources