Java数组创建、文件读写及学生成绩处理问题求助
Fixing Your Student Data File Reading & Array Population Issue
Hey there! Let's break down how to get past that file reading hurdle and finish up your Java program. You've got a solid start with your Student class and basic file setup—let's tweak a few things and fill in the gaps.
First: Fix the Student Class
Your current Student class has a couple of small adjustments needed to match your task requirements:
- The constructor was missing the
Finalgrade parameter (critical since your input data includes this field) - We'll auto-calculate the total score when creating a
Studentobject to avoid forgetting this step later - Switched to Java's standard camelCase naming conventions for readability
Here's the revised Student class:
public class Student { private String firstName; private String lastName; private double test1; private double test2; private double finalGrade; private double totalScore; // Updated constructor with all required parameters public Student(String f, String l, double t1, double t2, double fGrade) { firstName = f; lastName = l; test1 = t1; test2 = t2; finalGrade = fGrade; calculateTotal(); // Auto-calculate total score on object creation } // Calculate total using the given formula public void calculateTotal() { totalScore = test1 * 0.2 + test2 * 0.2 + finalGrade * 0.6; } // Accessor methods (getters) for all properties public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public double getTest1() { return test1; } public double getTest2() { return test2; } public double getFinalGrade() { return finalGrade; } public double getTotalScore() { return totalScore; } }
Second: Fix File Reading & Array Population
Your AppStudent class had a few key gaps:
- You weren't reading the first line (student count) to initialize your array size
inputStream.next()only reads until whitespace—usenextLine()to capture full lines- Your split separator was too strict (we'll use a regex to handle optional spaces around colons)
- You weren't parsing numeric values or creating
Studentobjects to fill the array - No code to write results to
Result.txt
Here's the complete, working AppStudent class:
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class AppStudent { public static void main(String[] args) { Student[] studentArray; String inputFileName = "students.txt"; String outputFileName = "Result.txt"; Scanner inputStream = null; PrintWriter outputStream = null; try { // Open input file inputStream = new Scanner(new File(inputFileName)); // First line is student count—initialize array with this size int studentCount = Integer.parseInt(inputStream.nextLine().trim()); studentArray = new Student[studentCount]; double totalClassScore = 0.0; // Loop through each student's data line for (int i = 0; i < studentCount; i++) { if (inputStream.hasNextLine()) { String line = inputStream.nextLine().trim(); // Split on colon, handling optional spaces around it String[] fields = line.split("\\s*:\\s*"); // Parse each field to correct data types String firstName = fields[0]; String lastName = fields[1]; double test1 = Double.parseDouble(fields[2]); double test2 = Double.parseDouble(fields[3]); double finalGrade = Double.parseDouble(fields[4]); // Create Student object and add to array studentArray[i] = new Student(firstName, lastName, test1, test2, finalGrade); // Accumulate total score for class average totalClassScore += studentArray[i].getTotalScore(); } } // Calculate class average total score double averageScore = totalClassScore / studentCount; // Open output file to write results outputStream = new PrintWriter(new File(outputFileName)); // Write passing students (total ≥60) outputStream.println("Students with passing total score (≥60):"); for (Student student : studentArray) { if (student.getTotalScore() >= 60) { outputStream.printf("%s %s - Test1: %.1f, Test2: %.1f, Final: %.1f, Total: %.1f%n", student.getFirstName(), student.getLastName(), student.getTest1(), student.getTest2(), student.getFinalGrade(), student.getTotalScore()); } } // Write class average outputStream.printf("%nClass average total score: %.1f%n", averageScore); System.out.println("Success! Results written to " + outputFileName); } catch (FileNotFoundException e) { System.out.println("Error: Could not find or open file " + inputFileName); System.exit(1); } finally { // Always close streams to avoid resource leaks if (inputStream != null) inputStream.close(); if (outputStream != null) outputStream.close(); } } }
Key Fixes & Notes:
- Array initialization: We read the first line of
students.txtto create an array of the exact size needed, avoiding wasted space. - Line handling:
nextLine()ensures we capture the entire student data line, not just a single word. - Flexible splitting:
split("\\s*:\\s*")works for bothJohn:Doe:80andJane : Smith : 75formats. - Auto-calculation: The
Studentconstructor callscalculateTotal()immediately, so we don't have to remember to do it manually. - Result writing: We use
PrintWriterto format and write passing students and the class average toResult.txt. - Resource cleanup: The
finallyblock ensures streams are closed even if an error occurs, preventing resource leaks.
Example students.txt Format:
Make sure your input file follows this structure:
3 John:Doe:80:90:85 Jane:Smith:55:60:50 Bob:Johnson:70:75:80
This should fully meet your task requirements. Let me know if you hit any other roadblocks!
内容的提问来源于stack exchange,提问作者Ghada
相关产品推荐
相关产品推荐

