繁体   English   中英

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

[英]How to read objects from an input file and write to an output file

我是计算机科学专业的学生,​​目前正在学习递归。 我正在做我的递归项目,并写一个输出文本文件,定于本周晚些时候。 这是一类学生(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

我知道我必须添加更多内容才能打印出最好的学生和荣誉学生的数量,但是现在我似乎无法弄清楚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

您的递归方法不正确。 他们根本不会读取输入文件,确定最佳学生或完全计数荣誉学生。

我使用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
 * 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();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM