如何将文本转换为对象的字段

时间:2014-06-06 20:49:52

标签: java variables char

好的,所以我有一个基本上是课程描述的文本文件。

Physics Applied SPH4C  2014

描述:     物理=课程名称     应用=课程水平     SPH4C =课程代码     2014年=学年

所以,我已经对这些信息进行了标记,以便每个字段都在一个单独的行上,如:

Physics
Applied
SPH4C
2014 

现在,我想将每一行转换为另一种类型,因为我的Course类接受不同的类型。

像这样:

public Course(String name, String code, char level, int academicYear)

如何将从文本文件中获取的字符串级别转换为char

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)

这就是我所拥有的,但它基本上只是更改了字符串,它不允许我将其作为一个级别输入,因为该课程只接受一个字符作为一个级别,或者我错了。

另外,我也需要学术水平方面的帮助 另外,我如何将每一行分配给变量

这是哈希表

    //This allows you to define your list with string keys instead of
//using a bunch of ifs.
Hashtable<String, char> CourseLevels = new Hashtable<String, char>()
                                                        {
                                                            put("IB", '7'),
                                                            put("Academic", '1'),
                                                            put("Applied", '1'),
                                                            put("ELL", '9'),
                                                            put("Special Education",    '8')
                                                        };

但是编译器告诉我第一个put语句需要返回类型,你可以用任何方式解决这个问题

这是编辑后的版本

    private char convertLevel(String courseLevel)
{
    //This allows you to define your list with string keys instead of
    //using a bunch of ifs.
    Hashtable<String, Object> courseLevels = new Hashtable<String, Object>();
    {
        courseLevels.put("IB", '7');

        courseLevels.put("Academic", '1');

        courseLevels.put("Applied", '1');

        courseLevels.put("ELL", '9');

        courseLevels.put("Special Education", '8');
    };
    //Determine if the courseLevel exists in our list.
    if (courseLevels.containsKey(courseLevel))
    {
        //Assuming level is defined as a char and not a string
        //Yes it does, use it.
        level = (char)courseLevels.get(courseLevel); // gives me an error
    }
    else
    {
        //if not use the default.    
        level = DEFAULT_LEVEL;
    }
    return level;
}

错误消息是不兼容的类型

这是整个班级

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++;

    setCourseFieldDescription();

    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)



private char convertLevel(String courseLevel)
{
    //This allows you to define your list with string keys instead of
    //using a bunch of ifs.
    Hashtable<String, Object> courseLevels = new Hashtable<String, Object>();
    {
        courseLevels.put("IB", '7');

        courseLevels.put("Academic", '1');

        courseLevels.put("Applied", '1');

        courseLevels.put("ELL", '9');

        courseLevels.put("Special Education", '8');
    };
    //Determine if the courseLevel exists in our list.
    if (courseLevels.containsKey(courseLevel))
    {
        //Assuming level is defined as a char and not a string
        //Yes it does, use it.
        level = courseLevels.get(courseLevel);
    }
    else
    {
        //if not use the default.    
        level = DEFAULT_LEVEL;
    }

}

// 
//         //Assuming level is defined as a char and not a string
//         if (CourseLevels.contains(courseLevel))
//         {
//             return CourseLevels.get(courseLevel);
//         }
//         else
//         {
//             return DEFAULT_LEVEL;
//         }

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

4 个答案:

答案 0 :(得分:0)

将1个字符更改为String类型可以通过以下方式完成:

myString.charAt(0);

答案 1 :(得分:0)

将String转换为您应该使用的char

"7".charAt(0); //first example;

你可以看看这个

In Java how does one turn a String into a char or a char into a String?

最后但并非最不重要的是,如果您要将字符串相互比较,则可能不会使用相等运算符,因为我认为您正在检查具有相同值的字符串。

为此你应该使用equals方法。我建议看看:

How do I compare strings in Java?

有关详细信息,请参阅java.lang.String

的官方文档

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

希望这会有所帮助:)

答案 2 :(得分:0)

调用函数时只需传递level.charAt(0)。

答案 3 :(得分:0)

如果您在文本文件中指示的课程级别为 SPH4C ,那么您无法将其设置为单个字符,只需将参数中的字符级别更改为即可。

比较两个字符串时,可以使用字符串

的equals方法

示例:

if(level.equals("IB")) level = "7";