文件扫描器仅读取文件中的最后一个数字。

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

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 &gt;= 90) {
			gradeA++; 
			scores++;
		}	else if (score &gt;=80) {
			gradeB++; 
			scores++;
		}	else if (score &gt;= 70) {
			gradeC++; 
			scores++;
		}	else if (score &gt;= 60) {
			gradeD++; 
			scores++;
		}	else if (score &gt;= 50) {
			gradeF++;
			scores++;
		}   else if (score &gt;100 || score &lt;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 &gt;= 90) { 
gradeA++; 
scores++; 
} 
else if (score &gt;=80) { 
gradeB++; 
scores++; 
} else if (score &gt;= 70) {
 gradeC++; 
scores++; 
} else if (score &gt;= 60) { 
gradeD++; 
scores++; 
} else if (score &gt;= 50) {
 gradeF++; 
scores++; 
} else if (score &gt;100 || score &lt;0) {
 uCount++; 
}
}

huangapple
  • 本文由 发表于 2020年10月21日 05:21:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64453496.html
匿名

发表评论

匿名网友

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

确定