0

一旦我正在搜索的项目在这种情况下显示为学生详细信息,我的搜索方法就有问题,它会输出 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
4

1 回答 1

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

示例:例如,您的数组长度为 10。

开始索引--->0

结束索引-----> 9

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

编辑:

找到学生后,使用break 语句跳出 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
      } 
于 2012-12-09T22:41:43.620 回答