英文:
File scanner only reading last number in file
问题
这是代码:
Scanner fileRead = new Scanner(file);
while (fileRead.hasNext()) {
score = (fileRead.nextInt());
}
if (score >= 90) {
gradeA++;
scores++;
} else if (score >= 80) {
gradeB++;
scores++;
} else if (score >= 70) {
gradeC++;
scores++;
} else if (score >= 60) {
gradeD++;
scores++;
} else if (score >= 50) {
gradeF++;
scores++;
} else if (score > 100 || score < 0) {
uCount++;
}
我应该计算分数的平均值,同时计算每个等级的数量。问题是它只读取最后一个数字,而不是大约 80 个不同的数字。
英文:
Here is the code:
Scanner fileRead = new Scanner(file);
while (fileRead.hasNext()) {
score = (fileRead.nextInt());
}
if (score >= 90) {
gradeA++;
scores++;
} else if (score >=80) {
gradeB++;
scores++;
} else if (score >= 70) {
gradeC++;
scores++;
} else if (score >= 60) {
gradeD++;
scores++;
} else if (score >= 50) {
gradeF++;
scores++;
} else if (score >100 || score <0) {
uCount++;
}
I'm supposed to be figuring out the average of scores, while counting how many are in each letter grade. The problem is that it only reads the last number instead of ~80 different numbers.
答案1
得分: 0
你的 if-else 逻辑直到 while 循环结束并且整个文件都被处理后才会被执行。意味着,只有最后一个 int 会被存储到 score 变量中。
将 while 循环的闭合括号移动到那个问题上会解决这个问题。
英文:
Your if-else logic doesn't get executed until the while loop ends and the entire file has been processed. Meaning, only the last int will be stored into score.
Moving the closing bracket of the while loop should fix that problem
答案2
得分: 0
你需要将你的 if else 条件放在 while 循环内部。
Scanner fileRead = new Scanner(file);
while (fileRead.hasNext()) {
score = (fileRead.nextInt());
if (score >= 90) {
gradeA++;
scores++;
}
else if (score >= 80) {
gradeB++;
scores++;
} else if (score >= 70) {
gradeC++;
scores++;
} else if (score >= 60) {
gradeD++;
scores++;
} else if (score >= 50) {
gradeF++;
scores++;
} else if (score > 100 || score < 0) {
uCount++;
}
}
英文:
You need to bring your if else condition inside the while loop.
Scanner fileRead = new Scanner(file);
while (fileRead.hasNext()) {
score = (fileRead.nextInt());
if (score >= 90) {
gradeA++;
scores++;
}
else if (score >=80) {
gradeB++;
scores++;
} else if (score >= 70) {
gradeC++;
scores++;
} else if (score >= 60) {
gradeD++;
scores++;
} else if (score >= 50) {
gradeF++;
scores++;
} else if (score >100 || score <0) {
uCount++;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论