英文:
How do I separate input lines in a file in string value and integer keys for Hash tables?
问题
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].trim());
String value = partition[0].trim();
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)
<details>
<summary>英文:</summary>
I want to get parse (if possible) the partition that contains the string that is a number(i.e."95") but I could accept any strategy to do it. my code works for hashMaps<string, string>
to not make this lengthy, this is how the lines in the input file look like:
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)
答案1
得分: 0
这只是我的猜测,但我认为值之间可能有多个空格。我将从分割命令中删除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);
}
}
英文:
This is a guess but I am assuming there could be more than one space between the values. And I remove the 2
from the split command. That was causing problems.
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);
}
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论