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

时间:2016-04-06 00:29:18

标签: java recursion file-io

我是一名计算机科学专业的学生,​​目前正在学习递归。我正在进行递归和写入输出文本文件的项目,将于本周晚些时候发布。这是一个学生班(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);
         }
     }
 }

TestRecursion类:

import java.util.*;
import java.io.*;
public class TestRecursion
{
    public static void main(String[] args) throws IOException
    {
        CS152 cs152 = new CS152();
        Scanner fileScan = new Scanner(new File("input.txt"));
        cs152.createList(fileScan);

        String file = "output.txt";

        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter outFile = new PrintWriter(bw);

        for(int line=1; line <= cs152.getSize(); line++)
        {
            for(int num=1; num <= cs152.getSize(); num++)
            {
                outFile.print(cs152);
            }
        }

        outFile.close();
        System.out.println("Output file has been created: " + file);
    }
}

输入文件:

Zombie Rob 0001 3.5 2013
Smith John 0002 3.2 2012
Jane Mary 0003 3.8 2014
Thekid Billy 0004 2.9 1850
Earp Wyatt 0005 1.5 1862
Holiday Doc 0006 1.4 1863
Cool Annie 0007 4.0 2013
Presley Elvis 0008 3.1 2011

我对每个学生的预期输出是:

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

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

2 个答案:

答案 0 :(得分:0)

您将内存地址分配给文件,这是@ 5abc3c12的内容。使用:

toString()

如果你想要文本,将非基元写入文件的方法。如果要在输出中使用格式,请使用

\n

并确保您不会在空间等方面崩溃。请记住添加分隔符以便能够从文件中获取数据。如果要存储完整对象,请查看序列化

答案 1 :(得分:0)

您的代码令人困惑。

这是我如何重构它。我的版本将此文本写入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

您的递归方法不正确。他们根本没有阅读输入文件,确定最佳学生,或者根本没有对学生进行正确评分。

我使用Java 8重构了代码。如果你是初学者,它可能太多了,但是它起作用并提供了一个如何以不同方式做到这一点的例子。

学生:

/**
 * 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:

/**
 * 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

永远不会太早
/**
 * 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();
        }
    }
}