I am a newbie Android Developer. I am trying to get a text input from user using and Edittext box and then convert that text into string and then into a char array of size 4. i have an array already stored that is of size 4 and it contains values. i want to compare both the arrays and perform a task based on the result.
I don’t know why am i getting the 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));
}
}
});
}
}
The problem is that
guesswordmay have fewer than four characters, and your code does not check for that condition.Change your code as follows to account for this condition:
Also note that your code as written does not “lock in” the
falsewhen characters are not equal to each other: for example,{'A','B','Z'}and{'X', 'Y', 'Z'}will compare equal under your old algorithm. Addbreakto exit the loop as soon as you see afalse.