0

so i have been trying to write a code to find Common characters in n strings. the code works fine on IntelliJ IDEA and onlinegdb(which has Interactive Console)but it does not work on other compilers and gives me this error:

>Exception in thread "main" java.lang.NullPointerException
    at Main.commonCharacters(Main.java:18)
    at Main.main(GFG.java:47)

had it not been an assignment,would be fine but the website which we have to submit the code does not have a Interactive Console and it's giving me Runtime error.

would appreciate any help.

import java.io.*;
import java.util.*;
import java.lang.*;
public class GFG {
  static int MAX_CHART = 26;
  public static void commonCharacters(String str[], int n)
  {
    Boolean[] prim = new Boolean[MAX_CHART];
    Arrays.fill(prim, new Boolean(true));
    for (int i = 0; i < n; i++) {

        Boolean[] sec = new Boolean[MAX_CHART];
        Arrays.fill(sec, Boolean.FALSE);

        for (int j = 0; j < str[i].length(); j++)
        {

            if (prim[str[i].charAt(j) - 'A'])// the compiler says the **problem** is here
               sec[str[i].charAt(j) - 'A'] = true;
        }

        System.arraycopy(sec, 0, prim, 0, MAX_CHART);
    }

    for (int i = 0; i < 26; i++)
        if (prim[i]){
            System.out.print(Character.toChars(i + 65));
        }
}

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

    Scanner input = new Scanner(System.in);
    int n = input.nextInt();// number of strings
    String[] str = new String[n];

    for (int i=0;i < n;i++){
        str[i]=reader.readLine();//getting strings as input
    }
    n = str.length;
    commonCharacters(str, n);
     }
 }

Pourya
  • 1
  • 1
  • 1
  • Why do you mix Scanner and BufferedReader to read from the console? And have you checked that you aren't supposed to provide the input to those compilers before starting the program? – Tom Apr 01 '21 at 18:40
  • the problem is when i want to get n inputs with a "for" loop and Scanner,it won't let me get the last input.for example if I enter 3 and then write ABC ,BDS the program finishes and does not let me to give the last input,it was because of that weird problem that i had to use BufferedReader – Pourya Apr 01 '21 at 18:59
  • by the way i provided the input before starting because if you don't, it will give you a new error – Pourya Apr 01 '21 at 19:02
  • If you provided the input beforehand, then it all should be fine. Regarding scanner, that problem isn't actually weird and there are many questions about that on stack overflow, [Scanner is skipping nextLine() after using next() or nextFoo()?](//stackoverflow.com/q/13102045) – Tom Apr 01 '21 at 23:13
  • 1
    thanks,actually i kinda fixed the problem by deleting the BufferedReader part and using just the "Input.next()" instead. – Pourya Apr 03 '21 at 14:21

0 Answers0