Displaying object values which are stored in a HashMap

Jonathan Dewein Source

I have a HashMap in which I have stored a string(key) and a Student object(value). I wish to iterate through the hash and display each key/value pair. However, I want to display the key followed by the String name value stored in the Student object. I have tried several ways and each one fails me in some way. I believe I do not entirely understand the "static" modifier, nor do I fully understand how to use HashMaps.

This is my full program:

import java.io.*;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Iterator;
public class FinalProgram {
    public static void main(String[] args) throws IOException {
        nameReader();
    }

    private static void nameReader() throws IOException {
        String nameFile = " ";
        String next = " ";
        int sNumber = 0;
        String formatSNumber = " ";
        String sName = " ";
        Scanner input = new Scanner(System.in);
        HashMap<String, Student> map = new HashMap<>();

        try {
            System.out.print("Enter the Name file(c:filename.txt): ");
            nameFile = input.nextLine();
        } catch(IllegalArgumentException e) {
            System.out.printf("Invalid input. Please enter"
                    + " filename in the form of "
                    + "c:filename.txt\n", e.getMessage());
        }
        //Instantiate FileReader and BufferedReader
        FileReader freader = new FileReader(nameFile);
        BufferedReader Breader = new BufferedReader(freader);
        boolean end = Breader.ready();

        do {
            next = Breader.readLine();
            sNumber = Integer.parseInt(next);
            formatSNumber = String.format("%03d", sNumber);
            sName = Breader.readLine();
            Student student = new Student(sName);
            map.put(formatSNumber, student);
            end = Breader.ready();
        } while(end);
        Iterator<String> keySetIterator = map.keySet().iterator();
        while(keySetIterator.hasNext()) {
            String key = keySetIterator.next();
            System.out.println("key: " + key + " value: " + map.get(Student.getName()));
        }
    }

This is my algorithm for reading the name file:

//Declaration of HashMap
HashMap<String, Student> map = new HashMap<>();

do {
            next = Breader.readLine();
            sNumber = Integer.parseInt(next);
            formatSNumber = String.format("%03d", sNumber);
            sName = Breader.readLine();
            Student student = new Student(sName);
            map.put(formatSNumber, student);
            end = Breader.ready();
        } while(end);
        Iterator<String> keySetIterator = map.keySet().iterator();
        while(keySetIterator.hasNext()) {
            String key = keySetIterator.next();
            System.out.println("key: " + key + " value: " +     map.get(key));
        }

This is my Student class(I have done both getters and setts and made a constructor since I am having issues which I will explain next:

public class Student {
    private String name = " ";
    public Student(String name) {
        this.name = name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    Course course = new Course();
}

Now, when I try to iterate through my map with:

while(keySetIterator.hasNext()) {
                String key = keySetIterator.next();
                System.out.println("key: " + key + " value: " +         map.get(key));
            }

The output is:

Enter the Name file(c:filename.txt): c:name.txt
key: 001 value: [email protected]
key: 002 value: [email protected]
key: 030 value: [email protected]

It stores the keys perfect, but I cannot get it to display the name of the Student object. I have tried static variables as well, but it returns null(I added 'static' to every variable and method in the Student class):

Enter the Name file(c:filename.txt): c:name.txt
key: 001 value: null
key: 002 value: null
key: 030 value: null

and when I try to call it directly:

System.out.println("key: " + key + " value: " + map.get(Student.getName()));

I receive the error:

Non-static method getName() cannot be referenced rom a static context.
javaobjecthashmapiterator

Answers

answered 2 years ago Dodd10x #1

If you don't provide a toString() implementation for your Student class, it prints the default which is what you are seeing. You can override toString().

public class Student {
    private String name = " ";
    public Student(String name) {
        this.name = name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    Course course = new Course();

    public String toString() {
        return name;
    }

}

As for Student.getName(), you are attempting to call a method on a class and not an instance of a class. Student.getName() is how you call a static method. You want to call something like key.getName() for a non-static method.

But that's not actually your problem. The correct syntax would be map.get(key).getName();

answered 2 years ago j.seashell #2

You're not accessing the Map() contents properly.

System.out.println("key: " + key + " value: " + map.get(Student.getName()));

The change would be:

System.out.println("key: " + key + " value: " + map.get(key).getName()));

You can think of it this way

Student student = map.get(key);
System.out.println("key: " + key + " value: " + student.getName());

Alternatively, you could edit you Student() class to be more static in context, as follows:

public class Student {
    private static String name = " ";
    public Student(String name) {
        this.name = name;
    }
    public static void setName(String name) {
        this.name = name;
    }
    public static String getName() {
        return name;
    }
    Course course = new Course();
}

This will get rid of the error: Non-static method getName() cannot be referenced rom a static context. However, I would not recommend making Student() more static. I would recommend the instantiation before the system out methodology.

Lastly, you could provide your own implementation of toString() in your Student() class:

public class Student {
    private String name = " ";

    // Your code here
    ...

    @Override
    public String toString() {
        return name;
    }
}

comments powered by Disqus