I was trying to split a String into a String array using the split function but received the error:
Exception in thread "main" java.lang.NullPointerException
at wdtbam.main(Main.java:16)
I was solving this problem at Codechef. My goal was to split the String into indexes of an array wherever a space was encountered and later parse that into Long type.
Here's my code
import java.util.*;
import java.io.*;
class wdtbam
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(br);
int t =sc.nextInt();
for(int i=1;i<=t;i++)
{
int n =sc.nextInt();
String a =br.readLine();
String b =br.readLine();
String c = br.readLine();
String cx[]= c.split(" "); //the problem
long d []=new long[1234];
int y=0;
for(int j=0;j<=n;j++)
{
d[j]=Long.parseLong(cx[j]);
}
for(int k=0;k<n;k++)
{
if(a.charAt(k)==b.charAt(k))
{
y++;
}
}
System.out.println(d[y]);
}
}
}
I have been encountering this problem since long and it would be very appcreciable if someone could help me out.
EDIT:
I removed BufferedReader from my code and instead used only Scanner. I also tried to directly input the numbers into an array instead of inputing a string and later parsing it to an long array.
Here's my new code:
import java.util.*;
import java.io.*;
class wdtbam
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t =sc.nextInt();
for(int i=1;i<=t;i++)
{
int n =sc.nextInt();
String a =sc.nextLine();
String b =sc.nextLine();
long d []=new long[1234];
int y=0;
for(int j=0;j<=n;j++)
{
d[j]=sc.nextInt();
}
for(int k=0;k<n;k++)
{
if(a.charAt(k)==b.charAt(k))
{
y++;
}
}
System.out.println(d[y]);
}
}
}
I am still getting an error. IDK why. Please help I am really frustrated with JAVA right now.
Error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at wdtbam.main(Main.java:18)
BTW here's the problem I was trying to solve : Codechef