Java 搜索方法,如果语句多次显示
在下面的代码中,我在lName数组中搜索姓氏,一旦在数组中找不到姓氏,每次循环中找不到姓氏时,else输出都会显示,我该如何解决这个问题?如果我在else部分添加returnfalse语句,它会在检查数组的第一个位置后停止循环 任何帮助都将受到感谢Java 搜索方法,如果语句多次显示,java,if-statement,for-loop,Java,If Statement,For Loop,在下面的代码中,我在lName数组中搜索姓氏,一旦在数组中找不到姓氏,每次循环中找不到姓氏时,else输出都会显示,我该如何解决这个问题?如果我在else部分添加returnfalse语句,它会在检查数组的第一个位置后停止循环 任何帮助都将受到感谢 public boolean search(String StudentlName) { boolean found = true; // set flag to true to begin first pass while
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;
}
如果未找到结果,则显示输出
找不到学生
找不到学生
找不到学生
找不到学生
找不到学生
在返回false之前,在循环外未找到打印学生。您只返回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
}
}
System.out.println("Student Not Found");
return false;
}
return true;
}
这将对您起作用,因为每当您错过要搜索的姓氏时,其他部分都会执行。为了简化,我相当肯定while循环没有任何好处。它总是在第一次迭代时返回,所以它是不必要的。因此,删除了find和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;
}
将来,您应该在发布代码之前正确格式化代码,以便人们更容易阅读。