Java 如何从输入文件读取对象并写入输出文件

Java 如何从输入文件读取对象并写入输出文件,java,recursion,file-io,Java,Recursion,File Io,我是一名计算机科学专业的学生,目前正在学习递归。我正在做关于递归和写入输出文本文件的项目,将于本周晚些时候完成。这是一个由学生组成的班级(CS152),它必须打印所有学生、最好的学生以及班级中的荣誉学生数量 学生班级: public class Student { String lastName, firstName, id; double gpa; int year; public Student(String lastName, String firstNa

我是一名计算机科学专业的学生,目前正在学习递归。我正在做关于递归和写入输出文本文件的项目,将于本周晚些时候完成。这是一个由学生组成的班级(CS152),它必须打印所有学生、最好的学生以及班级中的荣誉学生数量

学生班级:

public class Student
{
    String lastName, firstName, id;
    double gpa;
    int year;

    public Student(String lastName, String firstName, String id, double gpa, int year)
    {
        this.lastName = lastName;
        this.firstName = firstName;
        this.id = id;
        this.gpa = gpa;
        this.year = year;
    }

    public String toString()
    {
        String result = "NAME: " + lastName + ", " + firstName + "\n";

        result += "ID: " + id + "\n";
        result += "GPA: " + gpa + "\n";
        result += "YEAR: " + year + "\n";

        return result;
    }

    public boolean isHonors()
    {
        if (this.gpa > 3.5)
            return true;
        else
            return false;
    }

    public boolean isBetter(Student s)
    {   
        if(this.gpa > s.getGPA())
            return true;
        else
            return false;
    }

    public double getGPA()
    {
        return gpa;
    }

} 
CS152等级:

import java.util.*;
import java.io.*;

public class CS152
{
    public static final int MAXSIZE = 22;
    private static int size = 0;

    public CS152() throws IOException
    {
        Scanner fileScan;
        String firstName, lastName, id;
        double gpa;
        int year;

        fileScan = new Scanner(new File("input.txt"));

        createList(fileScan);
     }             

     public static Student[] createList(Scanner scan)
     {
         Student[] list = new Student[MAXSIZE];
         return populateList(list, scan);
     }

     private static Student[] populateList(Student[] list, Scanner scan)
     {
         Student s;
         if (size < MAXSIZE && scan.hasNext())
         {
             s = new Student(scan.next(), scan.next(), scan.next(), scan.nextDouble(), scan.nextInt());
             list[size] = s;
             size++;
             return populateList(list, scan);
         }
         else
             return list;
     }

     public static int getSize()
     {
         return size;
     }

     public static String toString(Student[] list, int n)
     {
         String str = "";
         if(n == 1)
         {
             str += list[0].toString();
         }
         else
         {
             str += list[n-1].toString();
             toString(list,n-1);
         }
     return str;
     }

     public static Student findBestStudent(Student[] list, int n)
     {
         if(n==1)
             return list[0];
         else
         {
             Student temp = findBestStudent(list, n-1);
             if(temp.isBetter(list[n-1]))
                 return temp;
             else
                 return list[n-1];
         }
     }

     public static int countHonors(Student[] list, int n)
     {
         if(n==0)
             return 0;
         else
         {
             if(list[n-1].isHonors())
                 return countHonors(list, n-1) + 1;
             else
                 return countHonors(list, n-1);
         }
     }
 }
我对每个学生的预期输出是:

NAME: Zombie Rob
ID: 0001
GPA: 3.5
YEAR: 2013

Best Student: (Whoever the best student is)
Amount of Honors Students: (amount of students)
我的输出文件如下所示:

CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12CS152@5abc3c12

我知道我必须添加更多内容才能打印出最佳学生和荣誉学生的数量,但现在我似乎无法确定我在CS152课程中的toString方法是否存在问题,或者我如何从文件中获取信息,或者我如何写入文件,或者是否存在其他问题。我完全迷路了。任何帮助都将不胜感激

您正在为文件分配内存地址,这就是@5abc3c12。使用:

toString()
方法将非原语写入文件(如果需要文本)。如果要在输出中设置格式,请使用

\n

并确保您不会撞到空间之类的东西。请记住添加分隔符以便能够从文件中提取数据。如果要存储完整的对象,请查看序列化

您的代码很混乱

下面是我如何重构它的。我的版本将此文本写入output.txt:

[Student{lastName='Zombie', firstName='Rob', id='0001', gpa=3.5, year=2013}, Student{lastName='Smith', firstName='John', id='0002', gpa=3.2, year=2012}, Student{lastName='Jane', firstName='Mary', id='0003', gpa=3.8, year=2014}, Student{lastName='Thekid', firstName='Billy', id='0004', gpa=2.9, year=1850}, Student{lastName='Earp', firstName='Wyatt', id='0005', gpa=1.5, year=1862}, Student{lastName='Holiday', firstName='Doc', id='0006', gpa=1.4, year=1863}, Student{lastName='Cool', firstName='Annie', id='0007', gpa=4.0, year=2013}, Student{lastName='Presley', firstName='Elvis', id='0008', gpa=3.1, year=2011}]
Best Student: Optional[Student{lastName='Cool', firstName='Annie', id='0007', gpa=4.0, year=2013}]
# of honors students: 2
您的递归方法不正确。他们根本没有正确地阅读输入文件、确定最佳学生或计算优等生

我使用Java8重构了代码。如果你是一个初学者,这可能太多了,但是它很有效,并且提供了一个不同的例子

学生:

/**
 * Student class
 * Created by Michael
 * Creation date 4/5/2016.
 * @link https://stackoverflow.com/questions/36439416/how-to-read-objects-from-an-input-file-and-write-to-an-output-file
 */
public class Student {
    private String lastName;
    private String firstName;
    private String id;
    private double gpa;
    private int year;

    public Student(String lastName, String firstName, String id, double gpa, int year) {
        this.lastName = lastName;
        this.firstName = firstName;
        this.id = id;
        this.gpa = gpa;
        this.year = year;
    }

    public boolean isHonors() {
        return this.gpa > 3.5;
    }

    public double getGpa() {
        return gpa;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("Student{");
        sb.append("lastName='").append(lastName).append('\'');
        sb.append(", firstName='").append(firstName).append('\'');
        sb.append(", id='").append(id).append('\'');
        sb.append(", gpa=").append(gpa);
        sb.append(", year=").append(year);
        sb.append('}');
        return sb.toString();
    }
}
学生工厂:

/**
 * StudentFactory
 * Created by Michael
 * Creation date 4/5/2016.
 * @link https://stackoverflow.com/questions/36439416/how-to-read-objects-from-an-input-file-and-write-to-an-output-file
 */

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;

public class StudentFactory {

    public List<Student> getStudentList(Scanner scanner) {
        List<Student> studentList = new ArrayList<>();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (StudentFactory.isNotBlank(line)) {
                String [] tokens = line.split("\\s+");
                studentList.add(new Student(tokens[0], tokens[1], tokens[2], Double.parseDouble(tokens[3]), Integer.parseInt(tokens[4])));
            }
        }
        return studentList;
    }

    public Optional<Student> getBestStudent(List<Student> studentList) {
        return studentList.stream().max(Comparator.comparing(Student::getGpa));
    }

    public long countHonors(List<Student> studentList) {
        return studentList.stream().filter(Student::isHonors).count();
    }

    public static boolean isNotBlank(String s) {
        return (s != null) && !"".equals(s.trim());
    }
}
/**
*学生工厂
*迈克尔创作的
*创建日期:2016年4月5日。
*@linkhttps://stackoverflow.com/questions/36439416/how-to-read-objects-from-an-input-file-and-write-to-an-output-file
*/
导入java.util.ArrayList;
导入java.util.Comparator;
导入java.util.List;
导入java.util.Optional;
导入java.util.Scanner;
公立学生工厂{
公共列表getStudentList(扫描仪){
List studentList=new ArrayList();
while(scanner.hasNextLine()){
字符串行=scanner.nextLine();
if(StudentFactory.isNotBlank(行)){
字符串[]标记=line.split(\\s+);
add(新学生(令牌[0]、令牌[1]、令牌[2]、Double.parseDouble(令牌[3])、Integer.parseInt(令牌[4]);
}
}
返回学生名单;
}
公共可选getBestStudent(列表studentList){
返回studentList.stream().max(Comparator.comparing(Student::getGpa));
}
公共长期荣誉(学生名单){
return studentList.stream().filter(Student::isHonors.count();
}
公共静态布尔值不为空(字符串s){
返回(s!=null)&&!“”.equals(s.trim());
}
}
了解以下方面永远都不为时尚早:

/**
*StudentFactory的JUnit测试
*迈克尔创作的
*创建日期:2016年4月5日。
*@linkhttps://stackoverflow.com/questions/36439416/how-to-read-objects-from-an-input-file-and-write-to-an-output-file
*/
导入org.junit.Assert;
导入org.junit.Before;
导入org.junit.Test;
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.io.FileWriter;
导入java.io.IOException;
导入java.io.PrintWriter;
导入java.util.List;
导入java.util.Scanner;
公开课学生工厂考试{
private StudentFactory StudentFactory=新StudentFactory();
私人名单学生名单;
@以前
public void setUp()引发FileNotFoundException{
Scanner fileScan=new Scanner(新文件(“./src/test/resources/input.txt”);
this.studentFactory=新studentFactory();
this.studentList=studentFactory.getStudentList(fileScan);
}
@试验
public void testGetStudentList()引发FileNotFoundException{
Assert.assertEquals(8,studentList.size());
}
@试验
public void testGetBestStudent(){
String expected=“可选[Student{lastName='Cool',firstName='Annie',id='0007',gpa=4.0,year=2013}]”;
Assert.assertEquals(应为this.studentFactory.getBestStudent(this.studentList.toString());
}
@试验
公共无效testCountHonors(){
Assert.assertEquals(2L,this.studentFactory.countHonors(this.studentList));
}
公共无效打印输出(字符串输出文件名){
try(PrintWriter pw=new PrintWriter(new FileWriter(outputFileName))){
println(这个学生名单);
println(“最佳学生:+studentFactory.getBestStudent(studentList));
println(“#荣誉学生:“+studentFactory.countHonors(studentList));
}捕获(IOE异常){
e、 printStackTrace();
}
}
}

了解如何覆盖对象中的toString()行为。您观察到的是java.lang.Object中的默认行为。你的学生班看起来不错;我猜你看到的是学生数组的引用。您需要在数组上循环,并对它包含的每个学生调用toString()。
/**
 * Student class
 * Created by Michael
 * Creation date 4/5/2016.
 * @link https://stackoverflow.com/questions/36439416/how-to-read-objects-from-an-input-file-and-write-to-an-output-file
 */
public class Student {
    private String lastName;
    private String firstName;
    private String id;
    private double gpa;
    private int year;

    public Student(String lastName, String firstName, String id, double gpa, int year) {
        this.lastName = lastName;
        this.firstName = firstName;
        this.id = id;
        this.gpa = gpa;
        this.year = year;
    }

    public boolean isHonors() {
        return this.gpa > 3.5;
    }

    public double getGpa() {
        return gpa;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("Student{");
        sb.append("lastName='").append(lastName).append('\'');
        sb.append(", firstName='").append(firstName).append('\'');
        sb.append(", id='").append(id).append('\'');
        sb.append(", gpa=").append(gpa);
        sb.append(", year=").append(year);
        sb.append('}');
        return sb.toString();
    }
}
/**
 * StudentFactory
 * Created by Michael
 * Creation date 4/5/2016.
 * @link https://stackoverflow.com/questions/36439416/how-to-read-objects-from-an-input-file-and-write-to-an-output-file
 */

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;

public class StudentFactory {

    public List<Student> getStudentList(Scanner scanner) {
        List<Student> studentList = new ArrayList<>();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (StudentFactory.isNotBlank(line)) {
                String [] tokens = line.split("\\s+");
                studentList.add(new Student(tokens[0], tokens[1], tokens[2], Double.parseDouble(tokens[3]), Integer.parseInt(tokens[4])));
            }
        }
        return studentList;
    }

    public Optional<Student> getBestStudent(List<Student> studentList) {
        return studentList.stream().max(Comparator.comparing(Student::getGpa));
    }

    public long countHonors(List<Student> studentList) {
        return studentList.stream().filter(Student::isHonors).count();
    }

    public static boolean isNotBlank(String s) {
        return (s != null) && !"".equals(s.trim());
    }
}
/**
 * JUnit test for StudentFactory
 * Created by Michael
 * Creation date 4/5/2016.
 * @link https://stackoverflow.com/questions/36439416/how-to-read-objects-from-an-input-file-and-write-to-an-output-file
 */

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Scanner;

public class StudentFactoryTest {

    private StudentFactory studentFactory = new StudentFactory();
    private List<Student> studentList;

    @Before
    public void setUp() throws FileNotFoundException {
        Scanner fileScan = new Scanner(new File("./src/test/resources/input.txt"));
        this.studentFactory = new StudentFactory();
        this.studentList = studentFactory.getStudentList(fileScan);
    }

    @Test
    public void testGetStudentList() throws FileNotFoundException {
        Assert.assertEquals(8, studentList.size());
    }

    @Test
    public void testGetBestStudent() {
        String expected = "Optional[Student{lastName='Cool', firstName='Annie', id='0007', gpa=4.0, year=2013}]";
        Assert.assertEquals(expected, this.studentFactory.getBestStudent(this.studentList).toString());
    }

    @Test
    public void testCountHonors() {
        Assert.assertEquals(2L, this.studentFactory.countHonors(this.studentList));
    }

    public void printOutput(String outputFileName) {
        try (PrintWriter pw = new PrintWriter(new FileWriter(outputFileName))) {
            pw.println(this.studentList);
            pw.println("best student: " + studentFactory.getBestStudent(studentList));
            pw.println("# of honors students: " + studentFactory.countHonors(studentList));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}