I'm trying to program a word unscrambler in java, but I keep getting this error Cannot read the array length because "contents" is null. I tried to use java.io.File, but it also gave me the same error when I tried it.
public static void main(String[] args) throws FileNotFoundException {
String[] contents = txtToString("allwords.txt");
Scanner in = new Scanner(System.in);
System.out.println("Insert your letters");
String input = in.nextLine();
char[] inputArray = input.toCharArray();
for(int i = 0; i < contents.length; i++)
{
for(int j = 0; j < contents[i].length()-1; j++)
{
char[] word = contents[i].toCharArray();
for(int c = 0; c < word.length-1; c++)
{
while(c<inputArray.length)
{
if(word[c]==inputArray[c])
{
word[j]=' ';
for(int s = 0; s < word.length-1;s++)
{
if(word[s]!= ' ')
{
break;
}
else
{
System.out.println("The word is "+contents[i]);
break;
}
}
}
}
}
}
}
}
private static String[] txtToString(String file) {
int count = 0;
try {
Scanner g = new Scanner(new File (file));
while(g.hasNextLine()) {
count++;
}
String[] textToArray = new String[count];
Scanner helloReader = new Scanner(new File(file));
for(int z = 0; z < count; z++) {
textToArray[z] = helloReader.next();
}
return textToArray;
}
catch (FileNotFoundException e){
}
return null;
}
Why am I getting this error?