0
我有一个看起来像如下解析用逗号分隔的文件,并等号
name=helium,sign=he,number=2
name=lithium,sign=li
name=gold,sign=au,number=79
名称,标志和数量都在地图中密钥的文件。如果某个键没有列出,它应该变成“未识别”值。现在我想解析这个逗号/等号分隔的文件,但是我没有成为我需要的结果,也找不到和改进错误。
这是我到目前为止有:
static Map<Table, String> periodicTable = new LinkedHashMap<Table, String>();
String[] list = fileToString(args[0]); // fileToString is to become the file content as a String array, where in the first field of the array is saved the first line of the file, in the second field - the second line and so on.
for (int i = 0; i < list.length; i++) {
String[] element = list[i].split(",");
for (int j = 0; j < element.length; j++) {
String[] feature = element[j].split("=");
if (feature[0].equals("name")
|| feature[0].equals("sign") || feature[0].equals("number")) {
feature[1] = periodicTable.get(feature[0]);
} else {
feature[1] = "unspecified";
}
}
}
public class Table {
private String name;
private String number;
private String sign;
public Table(String name, String number, String sign) {
this.name = name;
if (Integer.parseInt(number) >= 1 && Integer.parseInt(number) <= 118) {
this.number = number;
}
this.sign = sign;
}
}
这将是巨大的,如果有人可以帮助我这一个。提前致谢!
你期望些什么'periodicTable.get(feature [0]);'要做什么? (特别是因为'feature [0]'是'name','sign','number'之一?) – njzk2 2015-01-26 19:40:30
你的花括号是超级混淆。请先解决。 – HuStmpHrrr 2015-01-26 19:49:16
'feature [0]'是一个'String',你怎么试着从'Map
回答
不是一个解决方案,但你的代码的一些意见:
您解析文件中的代码是从主要的方法,我认为你错过了它,而不是分裂的地方
使用的StringTokenizer :
StringTokenizer tokenizer = new StringTokenizer(line,“,”); (tokenizer.hasMoreTokens()){ String element = tokenizer.nextToken(); }
使用的foreach的风格,而不是编入索引:
为(串行:list){上线 }
尝试使用 //富 “等于” 常量字符串的方法代替变量:
如果( “姓名” .equals(特征[0])){}
因为变量可以为空,瓦特这可能会破坏你的代码。
来源
2015-01-26 21:07:57 manzur
使您的方法更简洁的一个相对标准的方法是将元素属性封装在
enum
中。这样你可以很容易地扩展你正在存储的属性。它也避免了你的丑陋if
陈述。我已将Table
更改为Element
,因为对我而言,Table
将成为Element
的列表。那么你的阅读行代码可以是相当多的整洁:
我已经跳过了很多错误检查在这里,但希望你的想法。
来源
2015-01-27 00:03:07 sprinter
谢谢你的回答!有没有办法解决这个问题的一些类的Java API?地图,EnumMap或其他什么东西不会出现在我的脑海里? – Max55 2015-01-27 13:06:12
相关问题