0

I have a text file in the following format:

Student1 Marks
Student2 Marks

The first column is the key.

This is what I have tried so far

Scanner scanner = new Scanner(new FileReader("marks.txt"));

    HashMap<String,Integer> map = new HashMap<String,Integer>();

    while (scanner.hasNextLine()) {
        String[] columns = scanner.nextLine().split("\t");

        map.put(columns[0],columns[1]);
    }

    System.out.println(map);        


}
user3402248
  • 409
  • 6
  • 23

2 Answers2

1

Just make sure you parse the marks and that the values are indeed tab separated, otherwise code worked for me right away

    Scanner scanner = new Scanner(new FileReader("marks.txt"));

    HashMap<String,Integer> map = new HashMap<String,Integer>();

    while (scanner.hasNextLine()) {
        String[] columns = scanner.nextLine().split("\t");

        map.put(columns[0],Integer.parseInt(columns[1]));
    }

    System.out.println(map);        
Vasco Lameiras
  • 334
  • 2
  • 13
0

(With a little help from the comments) your code should be reading into the HashMap already, so i assume your problem is printing the HashMap after reading it in.

System.out.println(map) only gives you the representation of the map object. I suggest reading this: Convert HashMap.toString() back to HashMap in Java

To print all elements of that HasMap you could iterate over it, like shown here: Iterate through a HashMap

Community
  • 1
  • 1
Tanix
  • 106
  • 1
  • 8