簡體   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