Vaishavi Elayaraja
Vaishavi Elayaraja

Reputation: 1

Find non repeating character in a stream

First non-repeating character in a stream. I tried to solve this question in geeks for geeks and it is throwing an error.Can someone help me out? https://practice.geeksforgeeks.org/problems/first-non-repeating-character-in-a-stream/0#ExpectOP

import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
    
    public static void firstnonrepeatingcharacterinstream(char[] stream) {
        HashMap<Character,Integer> h = new HashMap<>();
        Queue<Character> q = new LinkedList<>();

        for(int i = 0; i < stream.length; i++) {
            h.put(stream[i], h.getorDefault(stream[i], 0) + 1);

            if(h.get(stream[i])==1) {
                q.add(stream[i]);
            }
        }
       
        while(!q.isEmpty()) {
            char c = q.peek();

            if(h.get(c) == 1) {
                break;
            } else {
                q.remove();
            }
        }

        if(q.isEmpty()) {
            System.out.print(-1 + "");
        } else {
            System.out.print(q.peek() + "");
        }
    }


    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int T = sc.nextInt();
        
        while (T-- > 0) {
            int N=sc.nextInt();

            char stream[]=new char[N];

            for(int i = 0; i < N; i++) {
                stream[i]=sc.next();
            }
            firstnonrepeatingcharacterinstream(stream);
        }
    }
}

I get this error:

Compilation Error

prog.java:12: error: cannot find symbol
       
 h.put(stream[i],h.getorDefault(stream[i],0)+1);
                         ^
  
symbol:   method getorDefault(char,int)
  
location: variable h of type HashMap<Character,Integer>

1 error

Upvotes: 0

Views: 126

Answers (1)

TheCreatingCoder
TheCreatingCoder

Reputation: 29

The first error

prog.java:12: error: cannot find symbol

h.put(stream[i],h.getorDefault(stream[i],0)+1); 

is because the Or is not capitalized like it should be. It should read the following:

h.put(stream[i],h.getOrDefault(stream[i],0)+1);

As for the other errors, they are due to you trying to convert an Object into a char improperly:

char c=q.peek();

As well as improperly try to convert a String to a char:

stream[i]=sc.next();

I hope this helps and good luck with the Interview Prep!

Upvotes: 1

Related Questions