Search code examples
javaarraysfor-looparr

New to Java: For some reason I get that the value is null in my for loop, but if I change i to 0 it is not null


The main problem is in the findFish method. I initialized i=0 in the for loop, but that gives me the error "Cannot invoke "com.company.Fish.getName()" because "this.fishInLake[x]" is null". However if I change i to for instance 0, it gives me false, which is the right result. Im a bit

package com.company;

import java.util.Arrays;

public class Lake {
    private String name;
    private double length;
    private double width;
    private double depth;
    private final int amountOfFish;
    private int currentFishAmount = 0 ;
    private Fish[] fishInLake;

    Lake(String name, double length, double width, double depth, int amountOfFish)
    {
        this.name = name;
        this.length = length;
        this.width = width;
        this.depth = depth;
        this.amountOfFish = amountOfFish;
        this.fishInLake = new Fish[amountOfFish];
    }

    public void addFish (String name, double length, double weight)
    {
        fishInLake[currentFishAmount]= new Fish(name, length, weight);
        System.out.println("Lake: " + this.name +  "|" + "Fish:" + ""+ fishInLake[currentFishAmount].getName() + fishInLake[currentFishAmount].getLength());
        System.out.println(currentFishAmount);
        currentFishAmount++;
        System.out.println(Arrays.toString(fishInLake));
    }

    **public boolean findFish(String fishName)
    {
        boolean isFound = false;
        for (int i = 0; i < fishInLake.length; i ++)
        {
            if (fishInLake[i].getName() == fishName)
            {
                isFound = true;
            }
        }
        return isFound;
    }**


}

Solution

  • The reason your code isn't working is because when you compare a null item using == or the equals() method, your code will throw an error. Also note that when working with Strings, you should use the .equals() method and not ==

    Here is a sample test case:

        System.out.println(n.findFish("shrimp"));
        System.out.println(n.findFish("babbgdshogj"));
    

    The expected output would be:

    true
    false
    

    The following code achieves that by making sure that the element in the array is not null:

    public boolean findFish(String fishName)
    {
        boolean isFound = false;
        for (int i = 0; i < fishInLake.length; i ++)
        {
            if (fishInLake[i] != null && fishInLake[i].getName().equals(fishName))
            {
                isFound = true;
            }
        }
        return isFound;
    }