在下面的代码中我在lName数组中搜索一个姓氏,一旦在数组中找不到姓氏,就会显示每次没有找到循环的else输出,我将如何解决这个问题?如果我在else部分添加一个return false语句,它会在检查数组的第一个位置后停止循环。
任何帮助都会得到满足!
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;
}
如果未找到结果,则显示输出
未找到学生
找不到学生
找不到学生
找不到学生
找不到学生
答案 0 :(得分:4)
在您返回false之前,在循环外打印“未找到学生”。你只返回一次假,然后你知道你没找到学生;不需要“其他”。
答案 1 :(得分:0)
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
}
}
System.out.println("Student Not Found");
return false;
}
return true;
}
这对你有用,因为每当你错过你想要搜索的姓氏时,其他部分就会执行。
答案 2 :(得分:0)
为了简化,我很确定while循环没有任何好处。它将始终返回它的第一次迭代,所以它是不必要的。所以删除了found和while循环后,我们就离开了。
public boolean search(String StudentlName)
{
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" );
return true;//Stops The Loop once Found
}
//Don't do anything when they aren't equal, except test the next one
}
//We checked everything, found nothing, So now print the message.
System.out.println("Student Not Found");
return false;
}