Alex
Alex

Reputation: 21

null value during putting value on map

I have a kind of problem. When I output my code, I get Id=null Name=null for the first entrance. Where is the problem may appear? Thanks.

public class Solution {
    HashMap<Integer, String> map;
    static Integer index;
    static String name;

    public Solution() {
        this.map = new HashMap<>();
        map.put(index, name);
    }

    public static void main(String[] args) throws IOException {
        Solution solution = new Solution();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        for (int i = 0; i < 10; i++) {
            int index = Integer.parseInt(reader.readLine());
            String name = reader.readLine();
            solution.map.put(index, name);
        }

        for (Map.Entry<Integer, String> pair : solution.map.entrySet()) {
            index = pair.getKey();
            name = pair.getValue();
            System.out.println("Id=" + index + " Name=" + name);
        }
    }
}

Here is the input: 1 str1 2 str2 3 str3 4 str4 5 str5 6 str6 7 str7 8 str8 9 str9 10 str10

Here is the output:

Id=null Name=null

Id=1 Name=str1

Id=2 Name=str2

Id=3 Name=str3

Id=4 Name=str4

Id=5 Name=str5

Id=6 Name=str6

Id=7 Name=str7

Id=8 Name=str8

Id=9 Name=str9

Id=10 Name=str10

Upvotes: 1

Views: 640

Answers (2)

prachi julka
prachi julka

Reputation: 76

You have added hashmap value in the constructor so the first value it contains is null. You should change it to as follows:-

public class Solution {
    HashMap<Integer, String> map;
    static Integer index;
    static String name;

    public Solution() {
        this.map = new HashMap<>();
    }

    public static void main(String[] args) throws IOException {
        Solution solution = new Solution();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        for (int i = 0; i < 1; i++) {
            int index = Integer.parseInt(reader.readLine());
            String name = reader.readLine();
            solution.map.put(index, name);
        }

        for (Map.Entry<Integer, String> pair : solution.map.entrySet()) {
            index = pair.getKey();
            name = pair.getValue();
            System.out.println("Id=" + index + " Name=" + name);
        }
    }


}

Removed map.put(index, name); from Solution constructor

Upvotes: 1

Uku Loskit
Uku Loskit

Reputation: 42040

 public Solution() {
        this.map = new HashMap<>();
        map.put(index, name); < ---
    }

notice this line. You are putting null values into the map in the constructor. Removing this line will fix the issue

Upvotes: 2

Related Questions