-4

Q: There are N strings. Each string's length is no more than 20 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this string occurred previously.

Sample Input

[Main List]

4

aba

baba

aba

xzxb

[Query]

3

aba

xzxb

ab

Sample Output

2 (aba appears twice appear in the main list)

1 (xzxb appears once in the main list)

0 (ab doesn't appear in the main list)

My Code

import java.util.*;

public class Solution {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

int N = scan.nextInt(); // CONTAINS N number of String
String word[] = new String[N]; //Sets N as size of an array


for(int i = 0; i < N; i++){
    word[i] = scan.nextLine();//Stores a word in every index of an array

}

scan.nextLine(); //Flush index??(need help?!)



 int Q = scan.nextInt(); // Stores number of query
   String searchWord[] = new String[Q];//integer for size of query array
    for(int i = 0; i <Q; i++){
        searchWord[i] = scan.nextLine(); // stores query array for comparison
    }


   int counter = 0; // initializing counter

   for(int i=0; i <Q; i++){//Take a query word and check if it exists in word[] 
       for(int j =0; j <N; j++ ){//searches for the query word in main List
           if(word[j] == searchWord[i]){// if it exists counter value adds +1
               counter++;
           }
       }
       System.out.println(counter); //print counter
       counter = 0; // reset counter

   }
    }
}

First of all the code does NOT work although the logic is seemingly correct (i guess). Also can someone explain me why we need to consume newline left-over by doing

input.nextLine();

src: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

Question : https://www.hackerrank.com/challenges/sparse-arrays

^^ And how do I use it in my question. Thank you! :)

Community
  • 1
  • 1
32sav
  • 15
  • 4

3 Answers3

0

The nextLine() is needed after a your call to nextInt() to consume any characters after the number ... including the newline.

(It is nothing to do with flushing indexes. What index??)

So ... it looks like you have it in the wrong place.

Stephen C
  • 632,615
  • 86
  • 730
  • 1,096
0

working code:

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter number of main list:");
    try {
        short mainListCount = Short.valueOf(br.readLine());
        // if count is valid then reading main list
        if (mainListCount > 0) {
            List<String> mainList = new ArrayList<>();
            while (mainListCount > 0) {
                mainList.add(br.readLine());
                mainListCount--;
            }

            // getting query count
            System.out.println("\nEnter number of Query:");
            short queryCount = Short.valueOf(br.readLine());
            if (queryCount > 0) {
                String queryStr;
                String result = "";
                while (queryCount > 0) {
                    queryStr = br.readLine();
                    result += " Occurance of " + queryStr + ": " + Collections.frequency(mainList, queryStr) + "\n";
                    queryCount--;
                }
                System.out.println("\n" + result);
            }
            System.out.println("\n\n**program ends**");
        } else {
            System.out.println("Invalid count");
        }
    } catch (NumberFormatException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

About scanner: A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. So when you do scan.next() or scan.nextInt() it reads till it encounters whitespaces. ex if you type 4 4 (space in between) it will take only 4 as value, and it doesn't read end of line "\n". scan.nextLine() read till the end of line. that's why scan.nextLine() after scan.next() is skipped because it reads "\n" (end of line) already present in the console because of 'Enter'.

Abhijeet
  • 11
  • 2
0

c# implementation but can be easily translated to java` '

int totalInputs = Convert.ToInt16(Console.ReadLine());
            Dictionary<string, int> dict = new Dictionary<string, int>();
            for(i = 0; i< totalInputs;i++)
            {
                string input = Console.ReadLine();
                if(dict.ContainsKey(input))
                {
                    dict[input]++;
                }
                else
                {
                    dict.Add(input, 1);
                }
            }
            int queries = Convert.ToInt16(Console.ReadLine());
            string[] queryString = new string[queries];
            for(i=0;i<queries;i++)
            {
                queryString[i] = Console.ReadLine();
            }
            foreach(string str in queryString)
            {
                if(dict.ContainsKey(str))
                {
                    Console.WriteLine(dict[str]);
                }
                else
                {
                    Console.WriteLine(0);
                }
            }

`

delwasaf ewrew
  • 428
  • 1
  • 7
  • 14