简体   繁体   English

在 android studio 中添加两个数字时出错

[英]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.我正在 Android Studio 中创建一个按钮,当在 Android Studio 中点击它时添加两个数字,但它给出了错误。 Can you help me?你能帮助我吗? I am a beginner in Android development.我是 Android 开发的初学者。

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 d4 是按钮的 id,inputField 是 EditText 的 id

Your setting int value to textView.您将 int 值设置为 textView。 so change int value into string like this所以像这样将int值更改为字符串

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 循环中看到了一些空洞,例如这个无效索引

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);
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM