Hi all,
I'm working on a simple Java project on student database. One of the methods I need to implement obviously involves searching for a student in the student registration using the student id input. Here is what I've been asked to do:
-searchStudentRegistration(String studentId): Using the studentId you will search
within the the studentRegistration array whether such a student exists or not. If it does
print all the student information by calling getStudentRegistrationInfo() or print
“Not Found”

and here is what I've done

private StudentRegistration[] stdreg;
public void searchStudentRegistration(String studentId){
        for(StudentRegistration s : stdreg){
            if(s.getStudent().getStudentId().equals(studentId)){
                System.out.println(s.getStudentRegistrationInfo());

            }     
            else{
                System.out.println("not found");
            }
        }

The problem I'm having is: the message 'not found' is printing even when there is a match. For instance, say the size of stdreg array is 3 and my 3 student id inputs are 001, 002 & 003. If I search for the student id 003 (which is obviously a match)- I get the outputs:
`

not found
not found
<student reg info>

From what I understand, negative the messages are being printed for every index where there is no match. Question is- how can I make the ''not found'' message print only once when there is no match- not any other time?
``

how can I make the ''not found'' message print only once

If you onlly want one message printed after the search ends, use a boolean variable (init to false) to record if a match is found(set to true). After the end of the loop if the boolean has not been set to true, then print the message.

If you onlly want one message printed after the search ends, use a boolean variable (init to false) to record if a match is found(set to true). After the end of the loop if the boolean has not been set to true, then print the message.

Ahh yes- Thanks!!! Can't believe I've spent ages for such a little twinkle! lol
Here's the corrected form of the code for those who may be facing the same problem in future:

public void searchStudentRegistration(String studentId){
        boolean found = false;
        for(StudentRegistration s : stdreg){
            if(s.getStudent().getStudentId().equals(studentId)){
                found  = true;
                System.out.println(s.getStudentRegistrationInfo());

            }     

        }
        if(found == false){
            System.out.println("not found");
        }

    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.