搜索方法帮助,

时间:2012-12-09 22:40:32

标签: java if-statement for-loop

我搜索方法的问题一旦我搜索的项目在这种情况下显示为学生详细信息,它输出if语句的“else”选项,下面是在此处使用的代码方法

public  void 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;
            }
            else
            {
                System.out.println("Student Not Found");
            }//End of If
        }// End of For
    }
}//end of search Method

这是我的菜单类的一部分,

        case 7:
                    System.out.println("Please Enter The Students
                                        you wish to find Last Name ");
                    String templName = keyb.nextLine();
                    System.out.println("");
                    myUnit.search(templName);
                    option = menuSystem();
                    break;

我认为它与for循环有关但我无法通过我的头脑。

一旦我输入了正确的姓氏(在这种情况下是“Scullion”),我想在这里出现:

HND Computing
Student ID = 0
Java
Daniel
Scullion
60
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
10 Student Not Found
Student Not Found
Student Not Found
Student Not Found
Student Not Found Student Not Found Student Not Found Student Not
Found Student Not Found

1 个答案:

答案 0 :(得分:1)

  for (int index = 0; index<= lName.length; index ++)

应该是

  for (int index = 0; index<lName.length; index ++)

数组索引基于零。即他们start index is 0 and the end-index is Arraylength-1

示例:对于isntance,您的数组长度为10.

开始指数---大于0

最终索引-----&GT; 9

如果您尝试访问高于9的索引,则 ArrayIndexOutOfBounds 将在运行时抛出。

编辑:

在找到学生后,使用break statement打破你的for循环。

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;
          break; //this will break outta the for-loop
      }