Skip to content
Advertisement

File scanner only reading last number in file

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.

Advertisement

Answer

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

9 People found this is helpful
Advertisement