【问题标题】:How to make text from textfile into fields of an object如何将文本文件中的文本转换为对象的字段
【发布时间】:2014-06-06 01:45:20
【问题描述】:

好的,我得到一个文本文件,对其进行标记,然后尝试将其写入另一个文件。

我有一个名为 course 的类,它有 4 个参数:名称、级别、代码、年份

我已将文本文件的每一行分成不同的行

@Edit:之前应该提到过,但我有 3000 门课程存储在一个文本文件中

public void readFromFile() throws IOException
{
    int index = 0;
    int j = -1;
    int spaceCount = 0;
    courseNumber++;

    setCourseFields();

    BufferedReader inputFile = new BufferedReader(new FileReader(INPUT_FILE));
    PrintWriter outputFile = new PrintWriter(new FileWriter(OUTPUT_FILE));

    String lineOfText = inputFile.readLine();

    while (lineOfText != null)        
    {
        outputFile.println(lineOfText);
        lineOfText = inputFile.readLine();

        for (char c : lineOfText.toCharArray()) 
        {
            if (c == ' ') 
            {
                spaceCount++;
            }
        }

        if(spaceCount == 1) 
        {
            delimiter = DELIMITER_SPACE;

        }
        else if(spaceCount == 2)
        {
            delimiter = DELIMITER_TAB;
        }

        System.out.println("Course" + courseNumber + "\n");

        // for each token in the string
        while ((j = lineOfText.indexOf(delimiter, (index = ++j))) != -1) 
        {
            System.out.println(courseField[k] + ": " + lineOfText.substring(index, j));
            counter++;
            k++;

        }

        // extract the last token
        if (index > 0)
        {
            System.out.println("Year: " + lineOfText.substring(index));
            ++courseNumber;
        }

        if(k == 3)
        {
            k = k - k;
            index = 0;
        }

        delayDisplay();

    } // while(lineOfText != null)

    inputFile.close();
    outputFile.close();
}

然后我会得到这样的东西

Course1

Name: Computer Engineering Technology
Level: IB
Code: TEJ4M
Year: 2017


Course2

Name: Communications Technology
Level: Special Education
Code: TGJ2O
Year: 2002

每门课程都是独一无二的,我需要帮助才能将上述每个字符串分配给一个变量。

每门课程有4个实例字段+一个唯一的序列号(Course Number)

这4个字段是:

String name;
char level;
String code;
int academicYear;

我想从 4 行中的每一行中制作课程

这是我的课程

public class Course extends Object implements Serializable
{
// class constants 
public static final String DEFAULT_CODE = "AAA10";
public static final char DEFAULT_LEVEL = 'X'; 
public static final String DEFAULT_NAME = "unassigned"; 
public static final int DEFAULT_YEAR = 1900;

private static final char ACADEMIC_LEVEL = '1'; 
private static final char ENGLISH_LANGUAGE_LEARNERS_LEVEL = '9';
private static final int ERROR_CODE = -1;
private static final char IB_LEVEL = '7';
private static final int MAXIMUM_YEAR = 2014;
private static final int MINIMUM_YEAR = 1900;
private static final char SPECIAL_EDUCATION_LEVEL = '8';

// instance variables 
private int academicYear;  
private String code; 
private static int counter = 0;
private char level; 
private String name;
private int serialNumber;

/**
 * Constructs a course with default characteristics.
 */
public Course()
{
    this.academicYear = DEFAULT_YEAR;
    this.code = DEFAULT_CODE;
    this.level = DEFAULT_LEVEL;
    this.name = DEFAULT_NAME;         
    serialNumber = ++counter;
} // end of constructor Course()

/** 
 * Constructs a course with the specified characteristics.
 * 
 * @param name - the Ministry-assigned name of this course; 
 *      ex: Introduction to Computer Science
 * @param code - the Ministry-assigned code of this course; ex: ICS3U
 * @param level - one of the enumerated levels ex: '7', '1', '9', '8'
 * @param academicYear - a 4-digit year of the Gregorian calendar 
 *      set between a minimum and maximum year
 */
public Course(String name, String code, char level, int academicYear)
{
    if(name == null) 
    {
        this.name = DEFAULT_NAME; 
    }
    else
    {
        this.name = name;
    } // end of if(name == null)
    if(code == null) 
    {
        this.code = DEFAULT_CODE; 
    }
    else
    {
        this.code = code;
    } // end of if(code == null)
    if (level == IB_LEVEL || level == ACADEMIC_LEVEL 
    || level == ENGLISH_LANGUAGE_LEARNERS_LEVEL 
    || level == SPECIAL_EDUCATION_LEVEL)
    {
        this.level = level; 
    }
    else
    {
        this.level = DEFAULT_LEVEL;
    } // end of if (level == IB_LEVEL || level == ACADEMIC_LEVEL || level == 
   ENGLISH_LANGUAGE_LEARNERS_LEVEL || level == SPECIAL_EDUCATION_LEVEL )

    if (academicYear >= MINIMUM_YEAR && academicYear <= MAXIMUM_YEAR)
    {
        this.academicYear = academicYear;
    }
    else 
    {
        this.academicYear = DEFAULT_YEAR;
    } // end of (academicYear >= MINIMUM_YEAR && academicYear <= MAXIMUM_YEAR)
    serialNumber = ++counter;
} // end of constructor Course(String name, String code, char level, int academicYear) 

/* Comparison methods*/
/**
 * Indicates whether another object has a state identical to this object’s state.
 * 
 * @param otherCourse - the object whose state is compared to this object’s
 * 
 * @return true if the other object has an identical state; otherwise false
 */
public boolean equals(Object otherCourse) 
{         
    if(otherCourse == null) return false;
    if (this.getClass() != otherCourse.getClass()) return false;
    if (this == otherCourse) return true;

    // Typecasting Object otherCourse into a Course to compare objects' states
    Course course1 = (Course) otherCourse;

    if(serialNumber != course1.getSerialNumber()) return false; 
    if(academicYear != course1.getYear()) return false;
    if(level != course1.getLevel()) return false;
    if(code != course1.getCode()) return false;
    if(name != course1.getName()) return false;

    // needed to satisfy the compiler
    return true;

} // end of method boolean equals(Object course) 

/**
 * Indicates whether another object has a state identical to this object’s state,
 * ignoring each object's unique serial number.
 * 
 * @param otherCourse - the object whose state is compared to this object’s
 * 
 * @return true if the other object has an identical state; otherwise false
 */
public boolean equalsIgnoreSerial(Object otherObject) 
{
    if(otherObject == null) return false;
    if (this.getClass() != otherObject.getClass()) return false;
    boolean courseEquals;
    Course anotherCourse = (Course) otherObject;       
    // Ignore unique serial number of each course
    if(this.serialNumber == anotherCourse.getSerialNumber()) return false; 
    if(this.academicYear != anotherCourse.getYear()) return false; 
    else courseEquals = true;
    if(this.level != anotherCourse.getLevel()) return false; 
    else courseEquals = true;
    if(this.code != anotherCourse.getCode()) return false; 
    else courseEquals = true;
    if(this.name != anotherCourse.getName()) return false;
    else courseEquals = true;

    return courseEquals;
} // end of method boolean equalsIgnoreSerial(Object course

/**
 * Compares this Course to another.
 * 
 * @return a negative value, if this course should come before the other course; 
 * 0, if this course and the other course have equal states; 
 * a positive value if this course should come after the other course
 */
public int compareTo(Course otherCourse)
{
    int before = -1;
    int after = 1;
    int equals = 0;
    int resultCode = code.compareTo(otherCourse.getCode());
    int resultName = name.compareTo(otherCourse.getName());

    if(otherCourse == null) return -1; 
    if(this.equals(otherCourse)) return equals;

    if(serialNumber < otherCourse.getSerialNumber()) return before;
    if(serialNumber > otherCourse.getSerialNumber()) return after;

    if(academicYear < otherCourse.getYear()) return before;
    if(academicYear > otherCourse.getYear()) return after;

    if(!(sortLevel(level) == -1 || sortLevel(otherCourse.getLevel()) == -1))
    {
        if(sortLevel(level) < sortLevel(otherCourse.getLevel())) return before;
        if(sortLevel(level) > sortLevel(otherCourse.getLevel())) return after;
    } // end of if(!(sortLevel(level) == -1 || sortLevel(otherCourse.getLevel()) ==
                    -1))

    if(code.compareTo(otherCourse.getCode()) != 0) return resultCode;

    if(name.compareTo(otherCourse.getName()) != 0) return resultName;

    // neccessary to satisfy the compiler
    return 5;

} // end of public int compareTo(Course otherCourse)

/* utility methods*/
public static int sortLevel(char level) 
{ 
    /*************************************
    final char[] LEVEL = {'7', '1', '9', '8'};
    for (int index = 0; index < LEVEL.length; index++) 
    {
    if(LEVEL[index] == level) return index;
    if(LEVEL[index] != level) return ERROR_IO_EXCEPTION;
    } // end of for (int index = 0; index < LEVEL.length; index++)

    // error code for not found, should not be reached
    return -1;
     ****************************************/ //code taken from in class discussion

    final char[] LEVEL = {'7', '1', '9', '8'};
    for (int index = 0; index < LEVEL.length; index++) 
    {
        if(LEVEL[index] == level) return index;
        if(LEVEL[index] != level) return -1;
    } // end of for (int index = 0; index < LEVEL.length; index++)

    // error code for not found, should not be reached
    return ERROR_CODE;
} // end of public static int sortLevel(char level) 

/* accessors*/

/**
 * Returns the code of this course.
 * 
 * @returns Returns the code of this course
 */
public String getCode()
{
    return code;
} // end of method getCode()

/**
 * Returns the level of this course.
 * 
 * @return the level of this course
 */
public char getLevel()
{
    return level;
} // end of method getLevel()

/**
 * Returns the name of this course.
 * 
 * @return the name of this course.
 */
public String getName()
{
    return name;
} // end of method getName()

/**
 * Returns the unique serial number of this course.
 * 
 * @return the unique serial number of this course.
 */
public int getSerialNumber()
{
    return serialNumber;
} // end of method getSerialNumber()

/**
 * Returns the academic year of this course.
 * 
 * @return the 4-digit academic year of this course
 */
public int getYear()
{
    return academicYear;
} // end of method getYear()

/* mutators */
/**
 * Sets the code of this course.
 * 
 * @param newCode - the new code of this course.
 */
public void setCode(String newCode)
{
    if (newCode == null) return;
    this.code = newCode;
} // end of method setCode(String newCode)

/**
 * Sets the level of this course.
 * 
 * @param newLevel - one of the enumerated levels
 */
public void setLevel(char newLevel)
{
    if(newLevel == IB_LEVEL || newLevel == ACADEMIC_LEVEL || newLevel == 
    ENGLISH_LANGUAGE_LEARNERS_LEVEL || newLevel == SPECIAL_EDUCATION_LEVEL)
    {
        level = newLevel;
    }
    else
    {
        level = DEFAULT_LEVEL;
    } // end of if(newLevel == IB_LEVEL || newLevel == ACADEMIC_LEVEL || newLevel ==
      ENGLISH_LANGUAGE_LEARNERS_LEVEL || newLevel == SPECIAL_EDUCATION_LEVEL)
} // end of method setLevel(char newLevel)

/**
 * Sets the name of this course.
 * 
 * @param newName - the new name of this course
 */
public void setName(String newName)
{
    if (newName == null) return;
    this.name = newName;
} // end of method setName(String newName)

/**
 * Sets the academic year of this course.
 * 
 * @param newYear - the new 4-digit academic year of this course
 */
public void setYear(int newYear)
{
    if (newYear >= MINIMUM_YEAR && newYear <= MAXIMUM_YEAR)
    {
        this.academicYear = newYear;
    }
    else
    {
        academicYear = DEFAULT_YEAR;
    } // end of if (newYear >= MINIMUM_YEAR && newYear <= MAXIMUM_YEAR)
} // end of method setYear(int newYear)

/**
 * Returns a string representation of this course.
 * 
 * @override toString in class Object
 * 
 * @return a string representation of this course.
 */
public String toString()
{      
    return 
    this.getClass().getName() 
    +"[" 
    + "Serial Number: " + serialNumber
    + ", academic year: " + academicYear
    + ", level: " + level
    + ", code: " + code
    + ", name: " + name
    +"]";
} // end of String toString()

另外,我需要帮助将字符串转换为级别的 char 和学年的 int,任何想法

这是我的 CourseUtility 课程,尚未完成

public class CourseUtility
{
// class constants
private static final String INPUT_FILE = "courses.text";
private static final String OUTPUT_FILE = "CoursesTokenized.text";
private static int counter = 0;
private static int courseNumber = 0;
private static int k = 0;
private static final String DELIMITER_SPACE = " ";
private static final String DELIMITER_TAB = "\t";
String delimiter = DELIMITER_TAB;
private static final String DEFAULT_LEVEL = "X";

String name = "";
String code = "";
String year = "";
String level = "";
String lineOfText;
private static String[] courseField = new String[5];

/**
 * Constructor for objects of class CourseUtility
 */
public CourseUtility() throws IOException
{

}

public void readFromFile() throws IOException
{
    int index = 0;
    int j = -1;
    int spaceCount = 0;
    courseNumber++;

    setCourseFields();

    BufferedReader inputFile = new BufferedReader(new FileReader(INPUT_FILE));
    PrintWriter outputFile = new PrintWriter(new FileWriter(OUTPUT_FILE));

    String lineOfText = inputFile.readLine();
    while (lineOfText != null)        
    {
        for (char c : lineOfText.toCharArray()) 
        {
            if (c == ' ') 
            {
                spaceCount++;
            }
        }

        if(spaceCount == 1) 
        {
            delimiter = DELIMITER_SPACE;

        }
        else if(spaceCount == 2)
        {
            delimiter = DELIMITER_TAB;
        }

        System.out.println("Course" + courseNumber);

        // for each token in the string
        while ((j = lineOfText.indexOf(delimiter, (index = ++j))) != -1) 
        {                
            System.out.println(courseField[k] + ": " + lineOfText.substring(index, j));
            System.out.println("");
            outputFile.println(lineOfText.substring(index, j));
            counter++;
            k++;

        }

        // extract the last token
        if (index > 0)
        {
            System.out.println("Year: " + lineOfText.substring(index));
            outputFile.println(lineOfText.substring(index));
            ++courseNumber;
        }
        // for each token in the string
        //             Course c = new Course(hm.get("Name"), hm.get("Code"), 
hm.get("Level"), Integer.parseInt(hm.get("Year")) );
        //             System.out.println(c);

        if(k == 3)
        {
            k = k - k;
            index = 0;
        }

        delayDisplay();
        lineOfText = inputFile.readLine();

    } // while(lineOfText != null)

    inputFile.close();
    outputFile.close();
}

public CourseUtility(String name, String code, String level, String year)
{
    if(name == null) 
    {
        this.name = Course.DEFAULT_NAME; 
    }
    else
    {
        this.name = name;
    } // end of if(name == null)
    if(code == null) 
    {
        this.code = Course.DEFAULT_CODE; 
    }
    else
    {
        this.code = code;
    } // end of if(code == null)
    if(level == null) 
    {
        this.level = DEFAULT_LEVEL; 
    }
    else
    {
        this.level = level;
    } // end of if(level == null)
    if(year == null) 
    {
        this.year = null;; 
    }
    else
    {
        this.year = year;
    } // end of if(year == null)

}

private void delayDisplay()
{
    try 
    {
        Thread.sleep(1000);
    } catch(InterruptedException ex) 
    {
        Thread.currentThread().interrupt();
    } // end of try
} // end of method void delayDisplay()

private void convertLevel(String courseLevel)
{        
    level = DEFAULT_LEVEL;
    if(level == "IB") level = "7";
    if(level == "Academic")level = "1";
    if(level == "Applied") level = "1";
    if(level == "ELL") level = "9";
    if(level == "Special Education") level = "8";
} // end of method convertLevel(String courseLevel)

public void deleteCourse()
{

private void setCourseFields()
{
    courseField[0] = "Name";
    courseField[1] = "Level";
    courseField[2] = "Code";
    courseField[3] = "Year";
} // end of method setCourseFields()

}

【问题讨论】:

  • 那些不是参数。这些是您的类的属性(或实例变量或属性)。另外,不要大写 int。你的 Course 类有构造函数吗?
  • @EdwinTorres 是的
  • 你能发布你的课程吗?查看构造函数、变量等会有所帮助。您还需要提供唯一的序列号。那会从哪里来?
  • @EdwinTorres 我分享了我的课程课程
  • 顺便说一句,equals方法不应该像这样比较String,试试if(!name.equals (course1.getName())) return false;

标签: java variables text-files bufferedreader tokenize


【解决方案1】:

我想我看到了你的问题。您正在解析字段,但不保存它们。您可以做的一件事是在拥有字段后保存它们。将它们存储在 HashMap 中,其中键是字段的名称。然后使用您的 HashMap 检索字段并调用构造函数:

// for each token in the string
HashMap<String,String> hm = new HashMap<String,String>();  //NEW
while ((j = lineOfText.indexOf(delimiter, (index = ++j))) != -1) 
{
    hm.put(courseField[k], lineOfText.substring(index, j));  //NEW
    System.out.println(courseField[k] + ": " + lineOfText.substring(index, j));
    counter++;
    k++;

}

// extract the last token
if (index > 0)
{
    System.out.println("Year: " + lineOfText.substring(index));
    hm.put("Year", lineOfText.substring(index)); //NEW
    ++courseNumber;
}

//translate level string to a character
char lvl;
String sLevel = hm.get("Level");
if (sLevel.equals("IB"))
    lvl = '7';
else if (sLevel.equals("Special Education"))
    lvl = '8';
else if (sLevel.equals("Academic"))
    lvl = '8';
else if (sLevel.equals("English Language Learners"))
    lvl = '1';
else
    lvl = ' '; /* unknown level */

//create the Course object
Course c = new Course(hm.get("Name"), hm.get("Code"), lvl , Integer.parseInt(hm.get("Year")) );

【讨论】:

  • 我在一个文本文件中有 3000 门这样的课程,我将如何解决这个问题,比如创建对象
  • 好的,这是一个不同的问题。您应该在获取课程数据的同一循环内创建对象。获得所需的所有数据后,调用构造函数。
  • 这会创建 3000 门不同课程的课程数量
  • 检索字段并调用构造函数是什么意思
  • 当您调用 hm.get("Name") 时,它会检索存储在键“Name”下的值。这就是 HashMap 的工作原理。 HashMap 在您解析它们时临时存储您的字段。它会创建 3,000 门课程吗?那要看。您的 WHILE 循环是否显示所有 3,000 门课程?
猜你喜欢
  • 2014-07-28
  • 2014-09-02
  • 2014-03-25
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多