initialize all variables but still get NullPointerExceptions error

后端 未结 1 1758
生来不讨喜
生来不讨喜 2021-01-29 14:25

Here is the code:

public class Fisher{

    private String name;
    private Fish [] fishCaught;
    private int numFishCaught;
    private int keepSize;
    pub         


        
1条回答
  •  [愿得一人]
    2021-01-29 14:51

    catchAFish() is returning null and so your likes() is getting a null reference in likes when you call if(f1.getSpecies()=="Sunfish") because you are passing in if(likes(p.catchAFish())){ // the problem happens here.

    I don't see how goFishingIn() is is called, you don't supply that code. But you are most likely calling it with an sad empty pond.

    You either need to check for null before using the return value of catchAFish, or ensure that catchAFish will never return null. Right now it will.

    Okay - I see your main function. The problem is you are out fishing your pond.

      public Fish catchAFish(){
    
        int num= (int)(Math.random() * (numFish-1));
        if(fish[num]!=null && numFish>0){
          fff= fish[num];
          fish[num]= fish[numFish-1];
          fish[numFish-1]=null;
          numFish--;
          return fff;
        }
        else
          return null;
      }
    

    You initalize your array to 20, but each time you fish you are removing a whole Fish class, so when you call goFishingIn you are removing one Fish object from your fish array in pond.

    I think you want to remove a single fish, and once that fish species is all fished out fish[num] == 0, then remove the fish.

      public Fish catchAFish(){
    
        int num= (int)(Math.random() * (numFish-1));
        if(fish[num]!=null && numFish>0){
          fff= fish[num];
          fish[num]--;
          if (fish[num] == 0)
          { 
              // No more of this fish type, remove it from the pond.
              fish[num]= fish[numFish-1];
              fish[numFish-1]=null;
              numFish--;
          }
          return fff;
        }
        else
          return null;
      }
    

    0 讨论(0)
提交回复
热议问题