Home > Software design >  Why doesn't my ArrayList print out the output desired in Java?
Why doesn't my ArrayList print out the output desired in Java?

Time:11-13

Pretty new user here, we are learning about methods in Java and are trying to test them using an ArrayList but it is not giving the desired output.

Here are the two methods that I created:

// initialize the ArrayList declared in the class block and add some test data to it
private static void addTestData()
{
    listOfNumbers = new ArrayList<>();
    listOfNumbers.add(23);
    listOfNumbers.add(34);
    listOfNumbers.add(45);
    listOfNumbers.add(56);

}

// returns a true or a false value indicating if a number provided to it is present in an ArrayList
private static boolean listContains(int param1)
{
    boolean found = false;
    for (int x: listOfNumbers)
    {
        if (param1 == x) 
        {
            found = true;
        }
        else
            break;
    }
    return found;
}

And my goal is to test in the main method if "4" and "56" are a part of the ArrayList, so here is my code for that:

    boolean numberFound = false;
    addTestData();
    System.out.println("*** Testing ArrayList Search ***");
    System.out.println("I am going to test if the number 4 is in the ArrayList.");
    listContains(4);
    numberFound = false;
    
    if (numberFound = true)
        System.out.println("The number 4 was found.");
    else 
        System.out.println("The number 4 was not found.");
    
    
    System.out.println("");
    numberFound = false;
    addTestData();
    System.out.println("I am going to test if the number 56 is in the ArrayList");
    listContains(56);
    
    if (numberFound = true)
        System.out.println("The number 56 was found.");
    else 
        System.out.println("The number 56 was not found.");

My output tells me that 4 is a part of the ArrayList, when it is not, in fact. Any idea what to do?

Directions for main method

Directions for my method

My output

CodePudding user response:

  1. You are assigning rather than comparing if (numberFound = true). It should be if (numberFound == true), or rather simply if (numberFound).
  2. Your function listContains() returns a boolean whicih you need to assign to numberFound.
numberFound = listContains(4);

Or you can straight up use it in if condition,

if(listContains(4)) { }
  1. Your function listContains() has issue. It should return true if found and false if not after iterating over all elements, which you are not. Right on 1st iteration, if comparison is false, you are breaking the loop, which return false
for (int x: listOfNumbers)
{
    if (param1 == x) 
    {
        return true;
    }
}
return false;

if according to your class instruction

boolean found = false;
for (int x: listOfNumbers)
{
    if (param1 == x) 
    {
        found = true;
        break; // with this you can skip remaining unnecessary iteration
    }
}
return found;
  • Related