Rahul Bansal
Rahul Bansal

Reputation: 33

Error while adding two numbers in android studio

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

Answers (2)

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

Sasi Kumar
Sasi Kumar

Reputation: 13313

Your setting int value to textView. so change int value into string like this

inputField.setText(Add.toString());

Upvotes: 2

Related Questions