Android健康问卷应用两处问题求助:重复计分与空输入崩溃
解决你的Android健康测验应用问题
我来帮你搞定这两个头疼的问题,咱们一个一个拆解:
问题1:多次点击结果按钮时累加之前的得分
你现在的核心问题是:前4道单选题的得分是在用户点击选项时就直接加到health变量里了,而不是在点击结果按钮时统一计算。这就导致用户反复切换选项时,health会不断累加,每次点结果按钮都会用之前攒下来的分数,自然结果不对。
其实完全不需要依赖View参数就能把所有检查逻辑整合到overView方法里,直接通过RadioGroup获取选中项就行:
具体修改步骤:
- 先把XML里所有RadioButton的
android:onClick属性删掉(比如android:onClick="checkQuestionOne"这类都去掉),因为我们不再需要点击单选按钮时触发计分。 - 删掉Java里原来的
checkQuestionOne到checkQuestionFour方法,然后重写overView方法,统一计算所有题目得分:
public void overView(View view){ // 每次计算前先重置得分,避免累加 health = 0; // 检查问题1 RadioGroup group1 = findViewById(R.id.group1); int selectedId1 = group1.getCheckedRadioButtonId(); if(selectedId1 == R.id.question_one_yes){ health +=1; } // 检查问题2 RadioGroup group2 = findViewById(R.id.group2); int selectedId2 = group2.getCheckedRadioButtonId(); if(selectedId2 == R.id.question_two_yes){ health +=1; } // 检查问题3 RadioGroup group3 = findViewById(R.id.group3); int selectedId3 = group3.getCheckedRadioButtonId(); if(selectedId3 == R.id.question_three_no){ health +=1; } // 检查问题4 RadioGroup group4 = findViewById(R.id.group4); int selectedId4 = group4.getCheckedRadioButtonId(); if(selectedId4 == R.id.question_four_no){ health +=1; } // 检查问题5和6 checkQuestionFive(); checkQuestionSix(); Toast displayToast = Toast.makeText(this, health + " is your score. If it is 4 or above, you have a healthy life", Toast.LENGTH_LONG); displayToast.show(); }
这样每次点击结果按钮时,都会重新计算所有题目的得分,再也不会出现累加旧结果的问题。
问题2:EditText为空时应用崩溃
你的checkQuestionFive方法里判断逻辑写反了!你现在写的if (!TextUtils.isEmpty(...))意思是「当输入不为空时显示提示」,但我们要的是「输入为空时显示提示并停止后续操作」。现在的情况是:输入为空时,这个条件不成立,代码会直接执行Integer.parseInt,空字符串转整数必然抛出NumberFormatException,导致崩溃。
修复后的代码:
public void checkQuestionFive() { EditText gettingQuestionFive = findViewById(R.id.sleep_hours); String input = gettingQuestionFive.getText().toString().trim(); // 输入为空时显示提示,直接返回不执行后续逻辑 if (TextUtils.isEmpty(input)){ Toast displayError = Toast.makeText(this, "You missed question 5, please don't leave it blank", Toast.LENGTH_LONG); displayError.show(); return; } // 加try-catch防止用户输入非数字内容(比如字母)导致崩溃 try { int answerQuestionFive = Integer.parseInt(input); if (answerQuestionFive >= 7) { health ++; } } catch (NumberFormatException e) { Toast.makeText(this, "Please enter a valid number for question 5", Toast.LENGTH_LONG).show(); } }
我还帮你修正了提示里的拼写错误(plase改成please),加了try-catch块处理非数字输入的情况,让应用更健壮。
内容的提问来源于stack exchange,提问作者Martin Evtimov
相关产品推荐
相关产品推荐

