Search code examples
javaparsinghashtable

How do I separate input lines in a file in string value and integer keys for Hash tables?


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

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)

Solution

  • 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);
    
                }
            }