0

Error Screenshot on Imgur

The problem is on HackerRank under algorithms named Sparse Arrays. I am new to java and this is really messing up, I have tried Googling but I cannot figure out what is wrong here.

public class Solution {
private final static Scanner sc = new Scanner(System.in);

public static void main(String[] args) {
    List<Integer> integers = new ArrayList<Integer>();
    List<String> strings = new ArrayList<String>();
    List<String> queries = new ArrayList<String>();
    int n = sc.nextInt();
    sc.nextLine();
    for( int i = 0; i < n; i++) {
        strings.add(sc.nextLine());
    }
    int q = sc.nextInt();
    sc.nextLine();
    for( int j = 0; j < q; j++) {
        queries.add(sc.nextLine());
    }
    
    for( int k = 0; k < q; k++) {
        int count = 0;
        for( int m = 0; m < q; m++) {
            if(queries.get(k) == strings.get(m)) {
                count++;
                integers.add(count);
            }
        }
        
    }
    integers.forEach(System.out::println);
}

}

  • 1
    Since `if(queries.get(k) == strings.get(m))` is wrong your `integers` list remains empty. – Tom Jun 05 '21 at 19:48
  • In other words, don't use `==` to compare strings for equality, use `if(queries.get(k).equals(strings.get(m))) {` instead. – DevilsHnd - 退職した Jun 05 '21 at 19:59
  • Check the index before getting the value from the list else you will end up with out of bound exception `if (queries.size() > k && strings.size() > m && queries.get(k).equals(strings.get(m))) {` – Arunkumar Pushparaj Jun 05 '21 at 20:00

0 Answers0