英文:
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<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
答案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<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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论