使用Scanner读取.txt文件数字遇阻:无法显示数字及实现A-F分级等功能
Hey there! Let's work through this problem step by step. It sounds like you've got the file recognized, but the Scanner isn't pulling in the numbers like you expect. Let's start with fixing that reading issue, then build out the rest of the functionality (grading, min/max/average) together.
Step 1: Correctly Reading Numbers with Scanner
First, let's make sure your Scanner is properly looping through the file to grab all numbers. Common mistakes here are forgetting to loop, or not handling potential exceptions (like if the file has non-number values). Here's a solid base to start with:
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class GradeProcessor { public static void main(String[] args) { // Replace with your actual file path File gradeFile = new File("grades.txt"); ArrayList<Double> grades = new ArrayList<>(); try (Scanner scanner = new Scanner(gradeFile)) { // Loop through every number in the file (works for space-separated or line-separated numbers) while (scanner.hasNextDouble()) { double grade = scanner.nextDouble(); grades.add(grade); // Print each grade as we read it to verify System.out.println("Read grade: " + grade); } } catch (FileNotFoundException e) { System.out.println("Error: Could not find the file!"); e.printStackTrace(); } catch (Exception e) { System.out.println("Error reading the file—check for non-number values!"); e.printStackTrace(); } // If we have grades, proceed with calculations if (!grades.isEmpty()) { calculateStats(grades); assignLetterGrades(grades); } else { System.out.println("No grades were read from the file."); } } }
Key Notes Here:
- We use a try-with-resources block for the Scanner—this automatically closes the file when we're done, so you don't have to remember to call
scanner.close(). - The
while (scanner.hasNextDouble())loop ensures we only read valid numerical values, skipping any whitespace (including newlines). - We store grades in an
ArrayListso we can easily access them later for calculations and grading.
Step 2: Calculating Min, Max, and Average
Add this method to your class to compute the stats once you have the grades stored:
private static void calculateStats(ArrayList<Double> grades) { double min = grades.get(0); double max = grades.get(0); double sum = 0; for (double grade : grades) { sum += grade; if (grade < min) min = grade; if (grade > max) max = grade; } double average = sum / grades.size(); System.out.println("\n--- Grade Statistics ---"); System.out.println("Minimum Grade: " + min); System.out.println("Maximum Grade: " + max); System.out.printf("Average Grade: %.2f\n", average); // Formats to 2 decimal places }
Step 3: Assigning Letter Grades (A-F)
Add this method to map each numerical grade to a letter grade. Adjust the thresholds if your grading scale is different:
private static void assignLetterGrades(ArrayList<Double> grades) { System.out.println("\n--- Letter Grades ---"); for (double grade : grades) { char letterGrade; if (grade >= 90) { letterGrade = 'A'; } else if (grade >= 80) { letterGrade = 'B'; } else if (grade >= 70) { letterGrade = 'C'; } else if (grade >= 60) { letterGrade = 'D'; } else { letterGrade = 'F'; } System.out.printf("Numerical Grade: %.1f -> Letter Grade: %c\n", grade, letterGrade); } }
Troubleshooting Tips If You Still Can't Read Grades
- Double-check your file path: If the file is in your project's root folder, just use the filename like
"grades.txt". If it's in a subfolder, use something like"data/grades.txt". - Verify the file content: Make sure the file only contains numbers (no extra text, commas instead of periods for decimals, etc.). Scanner's
nextDouble()expects periods for decimal points. - Try printing
scanner.hasNext()to see if the Scanner is detecting any content at all. If it returnsfalse, the file might be empty or formatted incorrectly.
Give this code a shot—start with the reading part first, and confirm you see the "Read grade: X" lines in your console. Once that's working, the rest of the functionality should fall into place smoothly.
内容的提问来源于stack exchange,提问作者Jack Madden

