-1

在下面的代码中,我在 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;  
}

如果未找到结果,则显示输出

找不到

学生 找不到

学生 找不到学生 找不到

学生 找不到

学生

4

3 回答 3

4

在您返回 false 之前,在循环外打印“Student not found”。你只返回一次 false,然后你就知道你没有找到学生;不需要“其他”。

于 2012-12-10T17:37:32.063 回答
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;  
}

这对您有用,因为每次您错过要搜索的姓氏时,都会执行 else 部分。

于 2012-12-10T17:42:42.063 回答
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;
}
于 2012-12-10T17:45:25.573 回答