Aaron
Aaron

Reputation: 999

For looping through an array to print one statement java

My piece of code will take a Patient object, and loop through an array which stores patient object and if it matches, it will print out the message on the if statement which is all good. But If the patient is not there, I believe the else segment will print out everytime the patient is not in the waitinglist array. What I'm trying to accomplish is to make the "your patient is not on the waiting list" print once if it's not in the array? Any idea how to do this? I tried to think about a way to do this, but I believe there is a simple solution that my brain cannot just figure out.

public int findWaitingPosition (Patient patient)
{
    for (int i=0 ; i <= waitingList.length-1 ; i++)
    {
        if (waitingList[i].equals(patient))
        {
            System.out.println ("The patient is on waiting list: " + i+1);
        }
        else
        {
            System.out.println ("Your patient is not on the waiting list");
        }

    }

Upvotes: 0

Views: 100

Answers (2)

Guido Simone
Guido Simone

Reputation: 7952

I would use a temporary variable. Also it looks like your method is supposed to return the position of the patient in the array. In this snippet -1 means not found.

public int findWaitingPosition (Patient patient)
{
    int position = -1;
    for (int i=0 ; i <= waitingList.length-1 ; i++)
    {
        if (waitingList[i].equals(patient))
        {
            position = i;
            break;
        }
    }
    if (position >= 0)
        System.out.println ("The patient is on waiting list: " + i+1);
    else
        System.out.println ("Your patient is not on the waiting list");

    return position;
 }

Upvotes: 2

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

You can change your loop as follows:

boolean patientNotInList = true;
for (int i=0 ; i <= waitingList.length-1 ; i++)
{
    if (waitingList[i].equals(patient))
    {
        System.out.println ("The patient is on waiting list: " + i+1);
        patientNotInList = false;
        break; //you might want to break the loop once the object is found
    }
}
if(patientNotInList) {
    System.out.println ("Your patient is not on the waiting list");
}

Upvotes: 1

Related Questions