0

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?

  • 1
    Your `txtToString()` method returned `null` because the file was not found. Is it okay that this method returns `null`? – Progman Nov 24 '21 at 19:19
  • https://stackoverflow.com/q/218384/438992 Might be worth not swallowing the exception. – Dave Newton Nov 24 '21 at 19:20
  • Remove the `try` and `catch` from your txtToString method. Add `throws FileNotFoundException` to that method’s declaration. This will guarantee that you are clearly informed of any problems reading the file, and it will prevent your program from trying to proceed when the file could not be read. (You don’t want the program to keep going if it has no data, right?) – VGR Nov 25 '21 at 00:10

0 Answers0