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
  • 439
  • 6
  • 25

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
  • 344
  • 3
  • 15
  • Or juts do `split("\\s+")`, which will split by any number of whitespaces. – Tavo May 06 '15 at 15:38
  • It gives me an error:** The method put(String, Integer) in the type HashMap is not applicable for the arguments (String, String)** – user3402248 May 06 '15 at 15:42
  • @user3402248 That is the error I got when I ran your code. Just use Integer.parseInt on the second parameter of map.put() and the error will be fixed – Vasco Lameiras May 06 '15 at 15:45
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