Error while adding two numbers in android studio

huangapple go评论77阅读模式
英文:

Error while adding two numbers in android studio

问题

我在Android Studio中创建了一个按钮,在点击它时会在Android Studio中添加两个数字,但出现了错误。你能帮我吗?我是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是按钮的ID,inputField是EditText的ID。

英文:

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&lt;ch.length; i++){
                if(ch[i]==&#39;+&#39;){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

答案1

得分: 2

你正在将整数值设置给textView。所以像这样将整数值转换为字符串:

inputField.setText(Integer.toString(Add));
英文:

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

inputField.setText(Add.toString());

答案2

得分: 0

你没有发布代码的错误消息,但在检查您的代码片段时,我发现一些问题,比如在for循环中的无效索引:

for(i=0; i<ch.length; i++){
     if(ch[i]=='+'){
         int Add=ch[i-1]+ch[i+1];
                     ^--在这里当i为零时您尝试获取索引为-1的元素这将引发异常
         inputField.setText(Add);
     }
}
英文:

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&lt;ch.length; i++){
     if(ch[i]==&#39;+&#39;){
         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);
     }
}

huangapple
  • 本文由 发表于 2020年8月1日 18:43:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63204314.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定