why is this null again?

Discussion in 'Plugin Development' started by stelar7, Oct 28, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    stelar7

    so, why is this null?

    Code:java
    1. private int goldAmount(Player player) {
    2. int sendme = 0;
    3. for (ItemStack is : player.getInventory().getContents()) {
    4. if (is.getTypeId() == 266) { // this line
    5. sendme = sendme + is.getAmount();
    6. }
    7. }
    8. return sendme;
    9. }
     
  2. Offline

    coldandtired

    Are you sure that the player is being passed correctly?

    Also, I've never used getContents(), but does it get only the slots with items in, or does it return also empty slots (which wouldn't have a TypeId)?
     
  3. Can we see the exception you get? :)
     
  4. Offline

    jblaske

    player.getInventory().getContents() will always return 32 item stacks. So you need to test for null on each one, before trying to do anything. any empty slot in the inventory will come back as a null, rather than a valid ItemStack
     
  5. Offline

    iffa

    if (is != null && is.getTypeId() == 266) { // this line
     
    jblaske likes this.
  6. Offline

    jblaske

    Give them a chance to solve the problem themselves, else they won't really learn. Rather than just giving them fixed code, that just leads to more questions about other topics.
     
  7. Offline

    oyasunadev

    Adding on to what everyone else said. This shouldn't change anything, but it is good practice. Whenever using foreach loops you should make the variable final.

    private int goldAmount(Player player) {
    int sendme = 0;
    for (final ItemStack is : player.getInventory().getContents()) {
    if (is.getTypeId() == 266) { // this line
    sendme = sendme + is.getAmount();
    }
    }
    return sendme;
    }
     
  8. Offline

    ItsHarry

    Why?
     
  9. Offline

    oyasunadev

    Well it's proper programming. The variable is redefined so it makes sense to make it final, since is keeps getting created then destroyed.
     
Thread Status:
Not open for further replies.

Share This Page