如何在哈希表的字符串值和整数键中分隔文件中的输入行?
How do I separate input lines in a file in string value and integer keys for Hash tables?
我想解析(如果可能的话)包含数字字符串(即“95”)的分区,但我可以接受任何策略来执行此操作。我的代码适用于 hashMaps
为避免冗长,输入文件中的行如下所示:
Kostas_Antetokounmpo 37
public static void main (String[] args) throws IOException {
String path = "roster.txt";
String row;
Integer row1;
HashTable_NBA<Integer,String> roster = new HashTable_NBA<>();
BufferedReader read = new BufferedReader(new FileReader(path));
while ((row = read.readLine()) != null){
String[] partition = row.split(" ", 2);
if(partition.length >= 2){
Integer key = Integer.parseInt(partition[1]);
String value = partition[0];
roster.put(key, value);
}
}
System.out.println(roster);
}
}
//EDIT
//the errors are these
Exception in thread "main" java.lang.NumberFormatException: For input string: "37 "
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at HashTable_NBA.main(HashTable_NBA.java:161)
这是一个猜测,但我假设值之间可能有多个 space。然后我从拆分命令中删除 2
。那导致了问题。
while ((row = read.readLine()) != null){
String[] partition = row.split("\s+");
if(partition.length >= 2){
Integer key = Integer.parseInt(partition[1]);
String value = partition[0];
roster.put(key, value);
}
}
我想解析(如果可能的话)包含数字字符串(即“95”)的分区,但我可以接受任何策略来执行此操作。我的代码适用于 hashMaps
为避免冗长,输入文件中的行如下所示:
Kostas_Antetokounmpo 37
public static void main (String[] args) throws IOException {
String path = "roster.txt";
String row;
Integer row1;
HashTable_NBA<Integer,String> roster = new HashTable_NBA<>();
BufferedReader read = new BufferedReader(new FileReader(path));
while ((row = read.readLine()) != null){
String[] partition = row.split(" ", 2);
if(partition.length >= 2){
Integer key = Integer.parseInt(partition[1]);
String value = partition[0];
roster.put(key, value);
}
}
System.out.println(roster);
}
}
//EDIT
//the errors are these
Exception in thread "main" java.lang.NumberFormatException: For input string: "37 "
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at HashTable_NBA.main(HashTable_NBA.java:161)
这是一个猜测,但我假设值之间可能有多个 space。然后我从拆分命令中删除 2
。那导致了问题。
while ((row = read.readLine()) != null){
String[] partition = row.split("\s+");
if(partition.length >= 2){
Integer key = Integer.parseInt(partition[1]);
String value = partition[0];
roster.put(key, value);
}
}