Results 1 to 11 of 11
  1. #1
    Diz
    Diz is offline Member
    Join Date
    May 2011
    Posts
    4
    Rep Power
    0

    Default NullPointerException

    Hey. I have been getting the error message that my code produces a NullPointerException. I don't know why I am getting this message, so could someone help me out with this? This code uses a use created class, so I'll include the class as well as the code and the error message I get when I run it.
    Java Code:
       import java.util.*;
       public class WordCounter {
        
          static Scanner input = new Scanner(System.in);
          static String stopChars = " ,.?!";
       
          static final int CAPACITY = 1024;
          static Counter[] words = new Counter[CAPACITY];
          static int nextIndex = 0;
       
          static int indexOf(String S, Counter[] array, int limit) {
             int index = limit - 1;
             while((index >= 0) && (!S.equals(words[index].getString()))) {
                index = index - 1;
             }
             return index;
          }		
       					
          static int indexOfAnyOf(String S, String stopChars) {
             int result = S.length();
             for(int i=0; i<stopChars.length(); i++) {
                int index = S.indexOf(stopChars.charAt(i));
                if(index >= 0) {
                   result = Math.min(result,index);
                }
             }
             if(result == S.length()) {
                result = -1;
             }
             return result;
          }
          static int sort(String S, Counter[] array){
             for(int i = 0; i<= S.length(); i++){      
                int count = array[i].getCount();
                [COLOR="Yellow"]int nextCount = array[i+1].getCount();[/COLOR]
                while((count > nextCount) && (count <= S.length())){
                   int temp = nextCount;
                   nextCount = count;
                   count = temp;
                   nextIndex = nextIndex + 1;           
                }
             	
             }
             return nextIndex;
          }
       				
          public static void main(String[] args){
             System.out.println("PMJ's WordCounter ...");
             final String BLANK = " ";
             int total = 0;
             while(input.hasNext()) {
                String line = input.nextLine().trim() + BLANK;
                int i;
                do {
                   line = BLANK + line;
                   do {
                      line = line.substring(1);
                      i = indexOfAnyOf(line,stopChars);
                   } while(i == 0);
                   if(i > 0) {
                      String word = line.substring(0,i).toLowerCase();
                      line = line.substring(i).trim() + BLANK;
                      total = total + 1;
                      int index = indexOf(word,words,nextIndex);
                      if(index < 0) {
                         if(nextIndex < CAPACITY) {
                            words[nextIndex] = new Counter(word);
                            index = nextIndex;
                            nextIndex = nextIndex + 1;
                         }
                      }
                      words[index].increase();
                   }
                   [COLOR="Yellow"]sort(line, words);[/COLOR]
                } while(i > 0);
             }
             int accumulatedTotal = 0;
             for(int index=0; index<nextIndex; index++) {
                System.out.println(index+": "+words[index]);
                accumulatedTotal = accumulatedTotal + words[index].getCount();
             }
             System.out.println("Total = " + total);
             System.out.println("Accumulated Total = " + accumulatedTotal);
          }
       }
    This is the error message that I receive when I run the program:
    Java Code:
    Exception in thread "main" java.lang.NullPointerException
    	at WordCounter.sort(WordCounter.java:35)
    	at WordCounter.main(WordCounter.java:74)
    And here is the user class provided to me:
    Java Code:
    /**
     * The class Counter provides a representation for a string with an associated counter.
     * 
     * @author P.M.J.
     * @version 2011-05-15
     */
       public class Counter {
       
       // Instance Variable(s) 
       //========================================================================
          private String s;		//The string
          private int count;	//The associated counter
       
       // Constructor Method(s)
       //========================================================================
       
       /**
       * Constructor for objects of class Counter
       */
          public Counter (String S) {
          // Initialize each of the instance variables
             s = S;
             count = 0;
          }
       
       // Observer Method(s)
       //========================================================================
       
       /**
       * Returns the value of the string attribute.
       * 
       * @param  None
       * @return The value of the string attribute. 
       */
          public String getString() {
             return s;
          }
       	
       /**
       * Returns the value of the count attribute.
       * 
       * @param  None
       * @return The value of the count attribute. 
       */
          public int getCount(){
             return count;
          }
             // Mutator Method(s)
       //========================================================================
       
       /**
       * Advances the value of the count attribute.
       * 
       * @param  None
       * @return None 
       */
          public void increase() {
             count = count + 1;
          }
       
       // Standard Method(s)
       //========================================================================
       
       /**
       * Standard method that returns the current attribute values as a printable string.
       */
          public String toString() {
             return s + ", " + this.getCount();
          }
       
       }
    Attached Files Attached Files
    Last edited by Diz; 05-12-2011 at 11:54 PM. Reason: Sorry about the format. Hopefully this makes it more readable.

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Please edit your code to use code tags.
    [code]
    YOUR CODE HERE
    [/code]

    Also can you highlight the lines that generate the errors?

    You probably have something uninitialized but it's hard to find what without having the code formatted or without having access to which line is which.

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,619
    Rep Power
    23

    Default

    Please copy full text of error message and paste it here. Here is a sample:
    java.io.EOFException
    at java.io.DataInputStream.readInt(Unknown Source)
    at VoteSystem.main(VoteSystem.java:103)
    The full text has the line number and methods where the error occurred.

  4. #4
    Diz
    Diz is offline Member
    Join Date
    May 2011
    Posts
    4
    Rep Power
    0

    Default Fixed format

    Yea sorry about the format. Hopefully this is easier to read.

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,619
    Rep Power
    23

    Default

    at WordCounter.sort(WordCounter.java:35)
    at WordCounter.main(WordCounter.java:74)
    What variables on line 35 in WordCounter in the sort method are null? Add a print statement to show the values of all the variables on or near that line if you can't see which one it is.

  6. #6
    Diz
    Diz is offline Member
    Join Date
    May 2011
    Posts
    4
    Rep Power
    0

    Default

    I believe the variable int nextCount is reporting as null. I tried to print out it's value and I got the NullPointerException error message and it indicated the line where i typed the print statement. Therefore i believe that it is reporting that the index array[i+1] is null, but to my understanding of the code, that index shouldn't be null.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by Diz View Post
    I believe the variable int nextCount is reporting as null. I tried to print out it's value and I got the NullPointerException error message and it indicated the line where i typed the print statement. Therefore i believe that it is reporting that the index array[i+1] is null, but to my understanding of the code, that index shouldn't be null.
    An int variable can never be null. It has to be due to a reference variable, not a primitive variable.

  8. #8
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    382
    Rep Power
    3

    Default

    As has been stated earlier, using print (or println) can greatly help bugsquishing. Since the problem appears at "int nextCount = array[i+1].getCount();", print out all the variables that appear in there, one by one. You can always print a null-variable, after all.

  9. #9
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,755
    Rep Power
    7

    Default

    Wild guess

    The default value in a reference array is null. Therefore if you create an array and do not fill it, all the other values will be null.
    Java Code:
    String[] arr = new String[5];
    arr[0] = "one";
    arr[1] = "two";
    In the above code the array will be: "one", "two", null, null, null. If this is what your code is doing then when you loop over the array and i is 1 (at the "two" item) then doing i+1 will point at the null item after it. {shrug} Just guessing that this is what you might be doing.

  10. #10
    Diz
    Diz is offline Member
    Join Date
    May 2011
    Posts
    4
    Rep Power
    0

    Default

    I briefly edited the code and had it print out "null" if array[i+1] == null, and it ended up printing out null. I think this means that when I go to try and initialize int nextCount and assign it array[i+1].getCount() it returns the error message because for some reason the index [i+1] in the array holds the value null. If thats true, i don't understand why it is null at that index. It should have been populated earlier in the program.

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,619
    Rep Power
    23

    Default

    As Furbarable pointed out, int variables can NEVER be null.
    Did you read Junky's post?
    It's the contents of the variable array at the selected index that is null. The int index will always have a non-null value.
    BTW array is a poor name for a variable. Makes for confusion when talking about your code.

    What happens if you print: array[i+1]
    System.out.println("array[i+1]=" + array[i+1]);

Similar Threads

  1. NullPointerException
    By maxspyderweb in forum New To Java
    Replies: 5
    Last Post: 03-02-2011, 10:42 AM
  2. Nullpointerexception?
    By Pulgo in forum New To Java
    Replies: 5
    Last Post: 01-05-2011, 04:05 PM
  3. Why do I get a NullPointerException?
    By nessa203 in forum New To Java
    Replies: 5
    Last Post: 01-07-2010, 01:14 PM
  4. NullPointerException I NEED HELP
    By mayhewj7 in forum New To Java
    Replies: 2
    Last Post: 02-13-2009, 08:03 AM
  5. I get a NullPointerException and don't know why
    By hendrix79 in forum New To Java
    Replies: 9
    Last Post: 12-14-2008, 06:18 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •