Reputation: 33
I'm creating a button in Android Studio which adds two numbers when cicked on it in Android Studio but it is giving the error. Can you help me? I am a beginner in Android development.
d4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String str=inputField.getText().toString();
char[] ch=str.toCharArray();
int i;
for(i=0; i<ch.length; i++){
if(ch[i]=='+'){int Add=ch[i-1]+ch[i+1];
inputField.setText(Add);}
}
}
});
d4 is the id of the button and inputField is the id of the EditText
Upvotes: 1
Views: 165
Reputation: 48258
you aren't posting the error msg of the code but inspecting your snippet I see some cavities like this invalid index in the for loop
for(i=0; i<ch.length; i++){
if(ch[i]=='+'){
int Add=ch[i-1]+ch[i+1];
^--here: when i is zero, you read try to get the
element at index -1, this will cause an exception!
inputField.setText(Add);
}
}
Upvotes: 0
Reputation: 13313
Your setting int value to textView. so change int value into string like this
inputField.setText(Add.toString());
Upvotes: 2