首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >搜索方法帮助,

搜索方法帮助,
EN

Stack Overflow用户
提问于 2012-12-10 06:40:32
回答 1查看 60关注 0票数 0

我的搜索方法有问题一旦我搜索的项目在本例中显示的是学生的详细信息,它会输出if语句的"else“选项,下面是此方法中使用的代码

代码语言:javascript
运行
复制
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

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

代码语言:javascript
运行
复制
        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"),就会出现以下内容:

代码语言:javascript
运行
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-10 06:41:44

代码语言:javascript
运行
复制
  for (int index = 0; index<= lName.length; index ++)

应该是

代码语言:javascript
运行
复制
  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循环。

代码语言:javascript
运行
复制
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
      } 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13792641

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档