0

Not sure why it gives me the NullPointerException. Please help. I am pretty sure all the arrays are full, and i restricted all the loops not to go passed empty spaces.

import java.util.; import java.io.;

public class TextAnalysis {

public static void main (String [] args) throws IOException {
    String fileName = args[0];
    File file = new File(fileName);
    Scanner fileScanner = new Scanner(file);
    int MAX_WORDS = 10000;
    String[] words = new String[MAX_WORDS];
    int unique = 0;

    System.out.println("TEXT FILE STATISTICS");
    System.out.println("--------------------");
    System.out.println("Length of the longest word: " + longestWord(fileScanner));
    read(words, fileName);
    System.out.println("Number of words in file wordlist: " + wordList(words));
    System.out.println("Number of words in file: " + countWords(fileName) + "\n");
    System.out.println("Word-frequency statistics");
    lengthFrequency(words);
    System.out.println();
    System.out.println("Wordlist dump:");
    wordFrequency(words,fileName);
}

public static void wordFrequency(String[] words, String fileName) throws IOException{
    File file = new File(fileName);
    Scanner s = new Scanner(file);
    int [] array = new int [words.length];
    while(s.hasNext()) {
        String w = s.next();
        if(w!=null){
            for(int i = 0; i < words.length; i++){
                if(w.equals(words[i])){
                    array[i]++;
                }
            }
            for(int i = 0; i < words.length; i++){
            System.out.println(words[i] + ":" + array[i]);
            }
        }
    }
}

public static void lengthFrequency (String [] words) {
    int [] lengthTimes = new int[10];

    for(int i = 0; i < words.length; i++) {
        String w = words[i];
        if(w!=null){
            if(w.length() >= 10) {
            lengthTimes[9]++;
            } else {    
            lengthTimes[w.length()-1]++;
            }
        }
    }
    for(int j = 0; j < 10; j++) {
        System.out.println("Word-length " + (j+1) + ": " + lengthTimes[j]);
    }
}

public static String longestWord (Scanner s) {
    String longest = "";
    while (s.hasNext()) {
        String word = s.next();
        if (word.length() > longest.length()) {
            longest = word;
        }
    }
    return (longest.length() + " " + "(\"" + longest + "\")");
}

public static int countWords (String fileName) throws IOException {
    File file = new File(fileName);
    Scanner fileScanner = new Scanner(file); 
    int count = 0;

        while(fileScanner.hasNext()) {
            String word = fileScanner.next();
                count++;
        }
    return count;
}


public static void read(String[] words, String fileName) throws IOException{
    File file = new File(fileName);
    Scanner s = new Scanner(file);
    while (s.hasNext()) {
    String word = s.next();
    int i;
    for ( i=0; i < words.length && words[i] != null; i++ ) {
        words[i]=words[i].toLowerCase();
        if (words[i].equals(word)) {
            break;
        }
    }
    words[i] = word;
}
}

public static int wordList(String[] words) {
    int count = 0;
    while (words[count] != null) {
        count++;
    }
 return count; 
}

}

4 Answers4

1

Your String Array String[] words = new String[MAX_WORDS]; is not initialized,you are just declaring it.All its content is null,calling length method in line 31 will give you null pointer exception. `

Ravi Godara
  • 477
  • 4
  • 17
  • the i call the method read(words, fileName); and it fills that array with strings, after that line, the array is not empty anymore – Biatrixia155 Mar 12 '14 at 05:16
  • for loop in your read(words,fileName) is not executing.... so its not filling the array. Its still empty.because you are checking i < words.length && words[i] != null; here words[i] is null so for loop will not execute.hence it will be filled will nulls. – Ravi Godara Mar 12 '14 at 05:25
  • @Biatrixia155 Print it: `System.out.println(Arrays.toString(words));` and see it for your self – OscarRyz Mar 12 '14 at 05:27
  • The for-loop words. It's wrapped in a while loop and terminate on null indexes of words. The line under the for-loop will set the value at the earliest null index. – JustinDanielson Mar 12 '14 at 05:29
1

There are two problems with this code 1.You didn't do null check,although the array contains null values 2.Your array index from 0-8,if you wan't to get element at 9th index it will throw ArrayIndexOutOfBound Exception.

Your code should be like that

public static void lengthFrequency (String [] words) {
int [] lengthTimes = new int [9];

for(int i = 0; i < words.length; i++) {
    String w = words[i];
    if(null!=w) //This one added for null check
    {
  /*  if(w.length() >= 10) {
    lengthTimes[9]++;
    } else {    
    lengthTimes[w.length()-1]++;
    }
    }*/

//Don't need to check like that ...u can do like below

 for(int i = 0; i < words.length; i++) {
    String w = words[i];
    if(null!=w)
    {
        lengthTimes[i] =w.length();
    }
}
}


//here we should traverse upto length of the array.
for(int i = 0; i < lengthTimes.length; i++) { 
    System.out.println("Word-length " + (i+1) + ": " + lengthTimes[i]);
}

}

Skabdus
  • 210
  • 1
  • 11
  • checking for null made it work, thanks :) – Biatrixia155 Mar 12 '14 at 05:29
  • 1
    You could add the null check in the for-loop conditional like you did in another place in the code. This code sample still has the index out of bounds error related to "new int [9];" and "lengthTimes[9]++;" – JustinDanielson Mar 12 '14 at 05:36
  • Now the code is modified to get the length & put it in that index,whatever it's size – Skabdus Mar 12 '14 at 05:51
  • @Skabdus hey, i just added another method wordFrequency, and I want it to stop printing words and how many times they appeared in the text once there are no more words in a file. Now it prints like thousands of times – Biatrixia155 Mar 12 '14 at 06:10
  • i tried setting it to print only until s.hasNext(), but it prints hundreds of nulls anyway – Biatrixia155 Mar 12 '14 at 06:12
  • This things will happens because you are using array,where already size is fixed..if u don't assign values it will contain null values...better u can use ArrayList.. – Skabdus Mar 12 '14 at 06:20
0

Simple mistake. When you declare an array, it is from size 0 to n-1. This array only has indexes from 0 to 8.

int [] lengthTimes = new int [9];
//some code here
lengthTimes[9]++; // <- this is an error (this is line 29)

for(int i = 0; i < 10; i++) {
    System.out.println("Word-length " + (i+1) + ": " + lengthTimes[i]); // <- same error when i is 9. This is line 37
JustinDanielson
  • 3,055
  • 1
  • 16
  • 26
  • While this is *another* problem with this code, it has nothing to do with a `NullPointerException`. – Brian Roach Mar 12 '14 at 04:59
  • when i correct int [] lengthTimes = new int [10]; it still gives me the same error with the same lines – Biatrixia155 Mar 12 '14 at 05:01
  • 1
    @user2310289 But what? It will throw an `ArrayIndexOutOfBoundsException` – Brian Roach Mar 12 '14 at 05:02
  • @BrianRoach, did your comment just now contribute anything at all? Do you want me to delete this answer and wait for him to post asking about his index out of bounds exception? This community is pretty terrible sometimes... – JustinDanielson Mar 12 '14 at 05:02
  • i changed the lengthTimes arrays' size to 10, but nothing changed.. same error – Biatrixia155 Mar 12 '14 at 05:12
  • keep it at 10. I'm still looking at the code, but the NPE isn't jumping out at me. The only thing suspicious is the w.length(), but you said the array is initialized after read. – JustinDanielson Mar 12 '14 at 05:29
0

When you declare:

String[] words = new String[MAX_WORDS];

You're creating an array with MAX_WORDS of nulls, if your input file don't fill them all, you'll get a NullPointerException at what I think is line 37 in your original file:

 if(w.length() >= 10) { // if w is null this would throw Npe

To fix it you may use a List instead:

 List<String> words = new ArrayList<String>();
 ...
 words.add( aWord );

Or perhaps you can use a Set if you don't want to have repeated words.

OscarRyz
  • 184,433
  • 106
  • 369
  • 548