我的搜索方法有问题一旦我搜索的项目在本例中显示的是学生的详细信息,它会输出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发布于 2012-12-10 06:41:44
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
结束索引->9
如果您试图访问大于9的索引,将在运行时抛出ArrayIndexOutOfBounds。
编辑:
找到学生后,使用跳出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
} https://stackoverflow.com/questions/13792641
复制相似问题