Java程序无法正确输出升序排序的firstName至输出文件问题求助
Let's fix your code step by step—there are a few key issues causing the problems with your sorted first names output:
Key Problems in Your Original Code
Scanner gets exhausted after the first loop
You read the entire input file with the firstwhile (in.hasNext())loop, so the second loop trying to populate thesArrayList will never run (the Scanner is already at the end of the file). That's why you saw no output for the sorted names.Incorrect array conversion
When you trieds.toArray(new String[s.size()]), you're trying to convertstudentobjects directly to a String array. Since you didn't overridetoString()in thestudentclass, Java uses the default object-to-string conversion (which outputs memory addresses like[Ljava.lang.String;@880ec60).Redundant ArrayLists and unnecessary code
You used two separateArrayList<student>instances (ssands) for no reason, and yourgetavgmethod had redundant parameter passing (you were reassigning member variables from parameters when they were already set in the constructor).
Corrected Code
First, let's clean up the student class (following Java naming conventions for readability):
public class Student implements Comparable<Student> { private String fname; private String lname; private String major; private float grades1; private float grades2; private float grades3; public String getFname() { return fname; } public String getLname() { return lname; } private String getMajor() { return major; } public float getGrades1() { return grades1; } public float getGrades2() { return grades2; } public float getGrades3() { return grades3; } @Override public int compareTo(Student other) { // Sort by first name ascending (matches your requirement) return this.fname.compareTo(other.fname); } public Student(String f, String l, String m, float g1, float g2, float g3) { fname = f; lname = l; major = m; grades1 = g1; grades2 = g2; grades3 = g3; } // Simplified average calculation (uses existing member variables) public float getAvg() { return (grades1 + grades2 + grades3) / 3; } }
Now the corrected Main class:
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { // Write test input (unchanged from your original) PrintWriter pw1 = new PrintWriter("input.txt"); pw1.println("Mickey Mouse CS 98.7 67.8 23.5"); pw1.println("Minnie Mouse ENG 45.6 98.3 94.7"); pw1.println("Donald Duck NET 56.8 74.2 78.4"); pw1.println("Bob Builder CS 78.5 89.4 82.5"); pw1.println("Snow White MAT 56.6 32.4 56.6"); pw1.println("Hellen Keller CHEM 78.8 23.1 99.6"); pw1.println("Daffy Duck ENG 67.4 55.5 89.5"); pw1.println("Fred Flinstone MAT 45.3 87.4 38.9"); pw1.println("Daffy Duck CS 76.5 22.2 88.5"); pw1.println("Bugs Bunny NET 68.4 89.7 95.6"); pw1.println("Winnie Pooh CHEM 77.5 89.4 98.2"); pw1.close(); File inputFile = new File("input.txt"); generateStatsFile(inputFile); } public static void generateStatsFile(File inputFile) throws IOException { Scanner in = new Scanner(inputFile); ArrayList<Student> students = new ArrayList<>(); // Read all students once (no redundant loops) while (in.hasNext()) { String fname = in.next(); String lname = in.next(); String major = in.next(); float g1 = in.nextFloat(); float g2 = in.nextFloat(); float g3 = in.nextFloat(); students.add(new Student(fname, lname, major, g1, g2, g3)); } in.close(); PrintWriter output = new PrintWriter(new FileWriter("out.txt")); // Feature a: Output names and average grades output.println("=== Student Names & Average Grades ==="); for (Student student : students) { output.printf("%s %s %.1f%n", student.getFname(), student.getLname(), student.getAvg()); } // Feature b: Output sorted first names ascending output.println("\n=== Sorted First Names ==="); Collections.sort(students); // Uses the Comparable implementation in Student for (Student student : students) { output.println(student.getFname()); } output.close(); System.out.println("Output file generated successfully!"); } }
What Changed & Why
- Single ArrayList for all students: We only read the input file once, storing all students in one list to avoid scanner exhaustion.
- Simplified average calculation: The
getAvg()method now uses the student's existing grade variables instead of reassigning them from parameters. - Proper sorting: Since
StudentimplementsComparable<Student>,Collections.sort(students)automatically sorts by first name. If you prefer a more explicit approach, you can replaceCollections.sort(students)with:Collections.sort(students, (o1, o2) -> o1.getFname().compareTo(o2.getFname())); - Cleaned up naming: Followed Java's standard conventions (capitalized class/method names) to make the code easier to read and maintain.
When you run this, your out.txt will have both sections working correctly: the first with student names and averages, the second with first names sorted alphabetically in ascending order.
内容的提问来源于stack exchange,提问作者modadisi




