基本上,我得到了一个文件,其中包含有关人员的详细信息,每个人用新行分隔,例如“
name Marioka address 97 Garderners Road birthday 12-11-1982 \n
name Ada Lovelace gender woman\n
name James address 65 Watcher Avenue
“ 等等..
而且,我想将它们解析为 [Keyword : Value] 对数组,例如
{[Name, Marioka], [Address, 97 Gardeners Road], [Birthday, 12-11-1982]},
{[Name, Ada Lovelace], [Gender, Woman]}, and so on....
等等。关键字将是一组定义的单词,在上述情况下:姓名、地址、生日、性别等......
做这个的最好方式是什么?
我就是这样做的,它有效,但想知道是否有更好的解决方案。
private Map<String, String> readRecord(String record) {
Map<String, String> attributeValuePairs = new HashMap<String, String>();
Scanner scanner = new Scanner(record);
String attribute = "", value = "";
/*
* 1. Scan each word.
* 2. Find an attribute keyword and store it at "attribute".
* 3. Following words will be stored as "value" until the next keyword is found.
* 4. Return value-attribute pairs as HashMap
*/
while(scanner.hasNext()) {
String word = scanner.next();
if (this.isAttribute(word)) {
if (value.trim() != "") {
attributeValuePairs.put(attribute.trim(), value.trim());
value = "";
}
attribute = word;
} else {
value += word + " ";
}
}
if (value.trim() != "") attributeValuePairs.put(attribute, value);
scanner.close();
return attributeValuePairs;
}
private boolean isAttribute(String word) {
String[] attributes = {"name", "patientId",
"birthday", "phone", "email", "medicalHistory", "address"};
for (String attribute: attributes) {
if (word.equalsIgnoreCase(attribute)) return true;
}
return false;
}