in the below code im searching for a surname in the lName array, once the surname is not found in the array the else output is showing for each time it is not found going round the loop, how would i go about solving this? if i add a return false statement in the else part it stops the loop after checking the first position of the array.
any help will be appriciated!
public boolean search(String StudentlName)
{
boolean found = true; // set flag to true to begin first pass
while ( found ==true )
{
for (int index = 0; index<lName.length; index ++)
{
if (StudentlName.equalsIgnoreCase(lName[index]) )
{
System.out.println(course+"\n"+
"Student ID = \t"+index+"\n"+
unitTitle + "\n" +
fName[index] + "\n" +
lName[index] + "\n" +
Marks[index] + "\n" + "\n" );
found = false;
return true;//Stops The Loop once Found used to stop infinite loop
}
else
{
System.out.println("Student Not Found");
}
}
return false;
}
return true;
}
If the result is not found this is shown output
Student Not Found
Student Not Found
Student Not Found
Student Not Found
Student Not Found
Print “Student not found” outside the loop, right before you return false. You only return false once, and by then you know you didn’t find the student; no “else” required.