猿问

字符串数组的索引

我正在使用基本的密码和用户ID系统进行编码,但似乎无法弄清楚该索引问题。我知道数组的索引为0,在我的代码中,我正在经历while循环(我尝试了for循环,但遇到了同样的问题),使用输入的针检查数组的第i个位置。无论出于什么原因,我都会收到此错误:


Process: com.example.gabeskillerpcjr.assemblylineapp, PID: 17838 java.lang.ArrayIndexOutOfBoundsException: length=3; index=3

    at com.example.gabeskillerpcjr.assemblylineapp.FourDtForm.exportVarifaction(FourDtForm.java:350)

    at com.example.gabeskillerpcjr.assemblylineapp.FourDtForm$3.onClick(FourDtForm.java:264)

这是我简单的while循环,int我初始化为0:


public void exportVarifaction(){

    String[] PinsNums = new String[]{"1415","1678","1923"};

    String[] PinNames = new String[]{"admin","test","test1"};

    String tmp;

    boolean done = false;

    while (!done) {

        tmp = PinsNums[i];

        if (tmp.equals(keyPadNumsEntered)) {

            result = PinNames[i];

            loggedOn = true;

            done = true;

        } else {

            ++i;

            result = "no logon";

        }

    }

}


慕码人8056858
浏览 167回答 3
3回答

蛊毒传说

在整个数组上进行迭代后,您缺少停止循环的条件。例如:while (!done) {    tmp = PinsNums[i];    if (tmp.equals(keyPadNumsEntered)) {        result = PinNames[i];        loggedOn = true;        done = true;    } else {        ++i;        result = "no logon";    }    if (i == PinsNums.length) {        done = true;    }}

温温酱

您正在使用的while循环和完成的布尔值都完全没有必要。您收到此异常的原因是,如果'tmp'永远不等于'keyPadNumsEntered',该怎么办?它将继续进行迭代,从而导致IndexOutOfBoundsException。这将作为for循环更具可读性,并且应防止出现异常:public void exportVarifaction(){&nbsp; &nbsp; String[] PinsNums = new String[]{"1415","1678","1923"};&nbsp; &nbsp; String[] PinNames = new String[]{"admin","test","test1"};&nbsp; &nbsp; String tmp;&nbsp; &nbsp; for (int i = 0; i < PinsNums.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; tmp = PinsNums[i];&nbsp; &nbsp; &nbsp; &nbsp; if (tmp.equals(keyPadNumsEntered)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = PinNames[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; loggedOn = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; if (!loggedOn) {&nbsp; &nbsp; &nbsp; &nbsp; result = "no logon";&nbsp; &nbsp; }}

湖上湖

您需要通过检查变量i和数组的长度来检查数组上的循环是否完成。&nbsp;while (!done && i<PinsNums.length) {&nbsp; &nbsp; &nbsp; &nbsp; tmp = PinsNums[i];&nbsp; &nbsp; &nbsp; &nbsp; if (tmp.equals(keyPadNumsEntered)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = PinNames[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; loggedOn = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; done = true;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ++i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = "no logon";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答