ArrayIndexOutOfBoundsExecption:安卓

dro*_*hef 2 java arrays android indexoutofboundsexception

我是一名新手Android开发者.我试图从用户使用和编辑文本框获取文本输入,然后将该文本转换为字符串,然后转换为大小为4的字符数组.我已经存储了一个大小为4的数组,它包含值.我想比较两个数组并根据结果执行任务.

我不知道为什么我得到ArrayIndexOutOfBoundsExecption

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.newgame);

    Button submit = (Button) findViewById(R.id.guess);



    EditText guess = (EditText) findViewById(R.id.editText1);


    boolean c=false;

    char[] guessword;
    char[] appword = {'T', 'R', 'U', 'E'};
    guessword = guess.getText().toString().toCharArray();


    for(int i=0;i<appword.length;i++)
    {
        if(guessword[i]==appword[i])
        {
            c=true;
        }
        else
        {
            c=false;
        }
    }

    final boolean correct=c;        


    submit.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            if(correct){
                startActivity(new Intent(Newgame.this, Win.class));
            }
            else{
                startActivity(new Intent(Newgame.this, Loose.class));
            }

        }
    });



}
Run Code Online (Sandbox Code Playgroud)

}

das*_*ght 7

问题是guessword可能少于四个字符,并且您的代码不会检查该条件.

如下更改您的代码以解决此问题:

for(int i=0;i<appword.length;i++)
{
    if((i < guessword.length) && (guessword[i]==appword[i]))
    {
        c=true;
    }
    else
    {
        c=false;
        break; // <<<=== Add this to end the loop
    }
}
Run Code Online (Sandbox Code Playgroud)

另请注意,所写的代码不会"锁定" false何时字符彼此不相等:例如,{'A','B','Z'}并且{'X', 'Y', 'Z'}在旧算法下将比较相等.一break看到,就加上退出循环false.