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


}
7
  • What is your question? How to print the map back? Commented May 6, 2015 at 15:31
  • it looks like if you split just on " " rather than "\t" it should work Commented May 6, 2015 at 15:31
  • also, you are putting a String value when it should be an Integer Commented May 6, 2015 at 15:32
  • 1
    @ControlAltDel: Since the split takes a regex, then I think that \s+ would work better. Commented May 6, 2015 at 15:32
  • 1
    or better yet, split with "\\s" Commented May 6, 2015 at 15:33

2 Answers 2

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);        
Sign up to request clarification or add additional context in comments.

3 Comments

Or juts do split("\\s+"), which will split by any number of whitespaces.
It gives me an error:** The method put(String, Integer) in the type HashMap<String,Integer> is not applicable for the arguments (String, String)**
@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
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.