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です。

start-Index ---> 0

end-index -----> 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 に答える