Android开发:循环、条件判断中分数累加异常问题求助
嘿,我一眼就看出问题出在哪了——你肯定是在更新分数的时候用了赋值操作(=)而不是累加操作(+=)!这就导致每次匹配到符合长度的条目时,分数都会被覆盖成当前条目的长度,而不是在之前的总分基础上加上这个长度。
咱们结合你的代码片段来修正,先看可能出错的地方:
假设你的原代码里是这样处理分数的:
try { reader = new BufferedReader(new InputStreamReader(getAssets().open("Words.txt"))); int i = 0; int f = 0; // 这里f是你的分数变量 String line; while ((line = reader.readLine()) != null) { // 这里是你判断用户输入和文本内容匹配的逻辑 if (/* 匹配条件 */) { int length = line.length(); if (length == 3 || length == 4 || length == 5) { f = length; // 问题就在这!每次都直接赋值,不是累加 } } } // 更新UI标签 scoreLabel.setText(String.valueOf(f)); } catch (IOException e) { e.printStackTrace(); }
只需要把赋值改成累加,再优化下代码的可读性,就能解决问题:
try { BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("Words.txt"))); int totalScore = 0; // 改名成totalScore更直观,避免歧义 String userInput = "替换成你的用户输入内容"; // 假设用户输入存在这里 String line; while ((line = reader.readLine()) != null) { String trimmedLine = line.trim(); // 先去掉前后空格,避免匹配出错 // 根据你的需求调整匹配逻辑,比如是否忽略大小写? if (trimmedLine.equals(userInput.trim())) { int wordLength = trimmedLine.length(); // 判断长度是否在3-5之间 if (wordLength >= 3 && wordLength <= 5) { totalScore += wordLength; // 关键!用累加操作替代赋值 } } } // 现在更新的就是累加后的总分了 scoreLabel.setText("总分: " + totalScore); reader.close(); // 记得关闭流,避免资源泄漏 } catch (IOException e) { e.printStackTrace(); }
另外再给你两个小建议:
- 用try-with-resources语法来管理流,它会自动帮你关闭资源,更安全:
try (BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("Words.txt")))) { // 这里写循环和分数计算逻辑,不用手动close() } catch (IOException e) { e.printStackTrace(); } - 确保你的分数变量是在循环外部初始化的,如果放在循环里,每次循环都会重置为0,也会导致无法累加。
内容的提问来源于stack exchange,提问作者Kyle Lebre
相关产品推荐
相关产品推荐

