Mona Jalal
Mona Jalal

Reputation: 38225

method always return null when trying to find the first non-repeating character in a String

I am trying to output the first non-repeating character in a string. However I am not sure what is wrong in my method as it always returns null. any hint is really welcomed.

public static char findRepeating(String s){

        HashMap<Character, Integer> charCount= new HashMap<>();

        for (Map.Entry<Character, Integer> entry: charCount.entrySet()){
            entry.setValue(0);
        }
        int count=0;
        for (int i=0; i<s.length(); i++){
            if (charCount.containsKey(s.charAt(i))){
                count=charCount.get(s.charAt(i));
                charCount.put(s.charAt(i), count++);
            }

        }
        for (Character ch:charCount.keySet()){
            if (charCount.get(ch)==0){
                return ch;
            }
        }
        return '\0';
    }

Upvotes: 1

Views: 65

Answers (2)

Eran
Eran

Reputation: 393936

Your problem is that this loop does nothing

    for (Map.Entry<Character, Integer> entry: charCount.entrySet()){
        entry.setValue(0);
    }

since the Map is empty.

As a result, if (charCount.containsKey(s.charAt(i))) is always false. You should add an else clause to initialize the count to 1 if the key is not found :

        if (charCount.containsKey(s.charAt(i))){
            count=charCount.get(s.charAt(i));
            charCount.put(s.charAt(i), ++count); // changed to pre-increment
        } else {
            charCount.put(s.charAt(i), 1);
        }

Also note that I changed count++ to ++count, since count++ returns the original value of count, so the value in the Map wouldn't change.

Upvotes: 1

Naruto
Naruto

Reputation: 4329

Because you are iterating through charcount which has no element in it.

Map.Entry<Character, Integer> entry: charCount.entrySet()

Upvotes: 0

Related Questions