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
Your setting int value to textView. so change int value into string like this
inputField.setText(Add.toString());
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.