Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: NullPointerException... Desperately need help

  1. #1
    Junior Member
    Join Date
    Oct 2017
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default NullPointerException... Desperately need help

    I am trying to create a Hash table using chaining method.

    I create an array of pointers that are all instantiated with data = 0 and pointer = null.

    I get the error "Exception in thread "main" java.lang.NullPointerException
    at HashChaining.main(HashChaining.java:341)"

    I am very confused and been trying to solve this for a while. I know it is a simple fix. I am especially confused because there should be no way that the getData() function would return null, it should only be able to return zero.

    The part that throws the exception:
    while (i < HashSize)
         {
               Node CurrentNode = HashTable[i];
               if (CurrentNode != null)
               {
                     NodeData = CurrentNode.getData();
               }
               if (NodeData != 0)
               {
                        System.out.println(i + ": ");
                        while(true)
                        {
     
                               System.out.println(CurrentNode.getData() + " ");
                               CurrentNode = CurrentNode.getLink();                                    <----------- Exception occurs on this line.
                               NodeData = CurrentNode.getData();
     
                               if (NodeData == 0)
                               {
                                      break;
                                }
                        }
                         i++;
                }
                else
                {
                         System.out.println(i + ": Empty");
                         i++;
                  }			
    }

    And the entire program:
    import java.util.*; 
    import java.io.*;
     
    /*String UserInputCommands = UserInput.nextLine();
    		String[] parts = UserInputCommands.split("\\.");
    		int size = Integer.parseInt(parts[0]);
    		HashTable = new Node[size];*/
     
    class Node
    {
        protected int data;
        protected Node link;
     
        /*  Constructor  */
        public Node()
        {
            link = null;
            data = 0;
        }    
        /*  Constructor  */
        public Node(int d,Node n)
        {
            data = d;
            link = n;
        }    
        /*  Function to set link to next Node  */
        public void setLink(Node n)
        {
            link = n;
        }    
        /*  Function to set data to current Node  */
        public void setData(int d)
        {
            data = d;
        }    
        /*  Function to get link to next node  */
        public Node getLink()
        {
            return link;
        }    
        /*  Function to get data from current Node  */
        public int getData()
        {
            return data;
        }
    }
     
    /* Class linkedList */
    class linkedList
    {
        protected Node start;
        protected Node end ;
        public int size ;
     
        /*  Constructor  */
        public linkedList()
        {
            start = null;
            end = null;
            size = 0;
        }
        /*  Function to check if list is empty  */
        public boolean isEmpty()
        {
            return start == null;
        }
        /*  Function to insert an element at begining  */
        public void insertAtStart(int val)
        {
    		Node nptr = new Node(val, null);    
    		size++ ;    
    		if(start == null) 
    		{
    			start = nptr;
    			end = start;
    		}
    		else 
    		{
    			nptr.setLink(start);
    			start = nptr;
    		}
        }
        /*  Function to insert an element at end  */
        public void insertAtEnd(int val)
        {
            Node nptr = new Node(val,null);    
            size++ ;    
            if(start == null) 
            {
                start = nptr;
                end = start;
            }
            else 
            {
                end.setLink(nptr);
                end = nptr;
            }
        }
        /*  Function to delete an element at position  */
        public void deleteAtPos(int pos)
        {        
            if (pos == 1) 
            {
                start = start.getLink();
                size--; 
                return ;
            }
            if (pos == size) 
            {
                Node s = start;
                Node t = start;
                while (s != end)
                {
                    t = s;
                    s = s.getLink();
                }
                end = t;
                end.setLink(null);
                size --;
                return;
            }
            Node ptr = start;
            pos = pos - 1 ;
            for (int i = 1; i < size - 1; i++) 
            {
                if (i == pos) 
                {
                    Node tmp = ptr.getLink();
                    tmp = tmp.getLink();
                    ptr.setLink(tmp);
                    break;
                }
                ptr = ptr.getLink();
            }
            size-- ;
        }    
        /*  Function to display elements  */
        public void display()
        {
            System.out.print("\nSingly Linked List = ");
            if (size == 0) 
            {
                System.out.print("empty\n");
                return;
            }    
            if (start.getLink() == null) 
            {
                System.out.println(start.getData() );
                return;
            }
            Node ptr = start;
            System.out.print(start.getData()+ "->");
            ptr = start.getLink();
            while (ptr.getLink() != null)
            {
                System.out.print(ptr.getData()+ "->");
                ptr = ptr.getLink();
            }
            System.out.print(ptr.getData()+ "\n");
        }
    }
     
    public class HashChaining
    {
    	public static void main(String[] args)
    	{
    		int HashSize = 10; //Default Size of Hash
    		Node[] HashTable = new Node[HashSize];
     
    		System.out.println("\n\n\n============================================================");
    		System.out.println("Welcome to the Chaining Hash tool.");
    		System.out.println("There are 3 commands: Insertion (X.in) Deletion (Y.del) Search (Z.sch)\n");
    		System.out.println("The Hash table is currently empty.\n");
    		System.out.println("Enter a series of commands in the format: \"1.in 2.in del 3.in ...\"\n");
     
    		Scanner UserInput = new Scanner(System.in);
    		String UserInputCommands = UserInput.nextLine();
     
    		int i = 0;
    		int j = 0;
    		int k = 0;
    		int NodeData = 0;
    		int HashIndex = 0;
    		int ContinueRunning = 1;
    		int singleCharInteger = 0;
    		int TemporaryHashValue = 0;
    		int CommandNumberLength = 0;
    		int UserInputLength = UserInputCommands.length();
     
    		String singleChar = "";
    		String CommandNumber = "";
    		String[] CommandNumberDigits = new String[3];
    		StringReader Commands = new StringReader(UserInputCommands);
     
    		/* while (i < HashSize)
    		{
    			HashTable[i].setData(0);
    			i++;
    		}
    		i = 0; */
     
    		while (ContinueRunning == 1)
    		{
    			while (i < UserInputLength - 1)
    			{
    				i++;
    				try
    				{
    					singleCharInteger = Commands.read();
    					singleChar = Character.toString((char) singleCharInteger);
    				}
    				catch(IOException err)
    				{
    					//
    				}
     
    				if ((singleChar.equals("0")) || (singleChar.equals("1")) || (singleChar.equals("2")) || (singleChar.equals("3")) || (singleChar.equals("4")) || (singleChar.equals("5")) || (singleChar.equals("6")) || (singleChar.equals("7")) || (singleChar.equals("8")) || (singleChar.equals("9")))
    				{
    					CommandNumberDigits[j] = singleChar;
    					j++;
    				}
    				else if (singleChar.equals("."))
    				{
    					StringBuilder ConcatenateCommandNumberDigits = new StringBuilder();
    					for(String s : CommandNumberDigits)
    					{
    						ConcatenateCommandNumberDigits.append(s);
    					}
     
    					CommandNumber = ConcatenateCommandNumberDigits.toString();
    					CommandNumberLength = CommandNumber.length();
     
    					StringReader RemoveNullsFromCommandNumber = new StringReader(CommandNumber);
     
    					while (k <= 3)
    					{
    						try
    						{
    							singleCharInteger = RemoveNullsFromCommandNumber.read();
    							singleChar = Character.toString((char) singleCharInteger);
    							if (singleChar.equals("n"))
    							{
    								break;
    							}
    							if (k == 3)
    							{
    								break;
    							}
    							k++;
    						}
    						catch(IOException err)
    						{
    							System.out.println("There was an error. This is most likely caused by input of a number greater than 3 digits.");
    						}
    					}
     
    					if (k == 1)
    					{	
    						CommandNumber = CommandNumber.substring(0,1);
    					}
    					else if (k == 2)
    					{
    						CommandNumber = CommandNumber.substring(0,2);
    					}
     
    					k = 0;
     
    					try
    					{
    						singleCharInteger = Commands.read();
    						singleChar = Character.toString((char) singleCharInteger);
    					}
    					catch(IOException err)
    					{
    						System.out.println("There was an error. This is most likely caused by input of a number greater than 3 digits.");
    					}
     
    					/////////////////////////////////////////////////////
    					if (singleChar.equals("i"))
    					{
    						TemporaryHashValue = Integer.parseInt(CommandNumber);
    						HashIndex = TemporaryHashValue % 10;
     
    						Node NewPointer = new Node(TemporaryHashValue, null);
     
    						if (HashTable[HashIndex] == null) 
    						{
    							HashTable[HashIndex] = NewPointer;
    						}
    						else 
    						{
    							Node PreviousHead = new Node(HashTable[HashIndex].getData(), null);
    							NewPointer.setLink(PreviousHead);
    						}
     
     
     
    						Arrays.fill(CommandNumberDigits, null);
    						j = 0;
    					}
     
    					/////////////////////////////////////////////////////
    					else if (singleChar.equals("d"))
    					{
     
     
     
     
    						Arrays.fill(CommandNumberDigits, null);
    						j = 0;
    					}
     
    					//////////////////////////////////////////////////////
    					else if (singleChar.equals("s"))
    					{
     
     
     
     
    						Arrays.fill(CommandNumberDigits, null);
    						j = 0;
    					}
    					/////////////////////////////////////////////////////
    				}
    			}
     
    			System.out.println("\nThe Hash table is currently:\n");
     
    			i = 0;
    			j = 0;
    			while (i < HashSize)
    			{
    				Node CurrentNode = HashTable[i];
    				if (CurrentNode != null)
    				{
    					NodeData = CurrentNode.getData();
    				}
    				if (NodeData != 0)
    				{
    					System.out.println(i + ": ");
    					while(true)
    					{
     
    						System.out.println(CurrentNode.getData() + " ");
    						CurrentNode = CurrentNode.getLink();
    						NodeData = CurrentNode.getData();
     
    						if (NodeData == 0)
    						{
    							break;
    						}
    					}
    					i++;
    				}
    				else
    				{
    					System.out.println(i + ": Empty");
    					i++;
    				}			
    			}
     
    			System.out.println(Arrays.toString(HashTable));
    			System.out.println("\nEnter another command or enter [/] to exit.\n");
    			String CommandOrStop = UserInput.nextLine();
    			if (CommandOrStop.equals("/"))
    			{
    				ContinueRunning = 0;
    			}
    			else
    			{
    				i = 0;
     
    				UserInputCommands = CommandOrStop;
    				UserInputLength = UserInputCommands.length();
     
    				Commands = new StringReader(UserInputCommands);
    			}
    		}
    		System.out.println("\nThe Hash program has finished");
    	}
    }
    Attached Images Attached Images
    Last edited by mikbferguson; October 18th, 2017 at 02:28 AM.

  2. #2
    Member
    Join Date
    Apr 2014
    Posts
    92
    Thanks
    3
    Thanked 7 Times in 7 Posts

    Default Re: NullPointerException... Desperately need help

    It looks like CurrentNode is null. Are you not getting a NullPointerException on this line, just above the one you marked in comments?
    System.out.println(CurrentNode.getData() + " ");
    Your HashTable array is populated based on user inputs. Are you sure every element in the array is guaranteed to be non-null?
    Node CurrentNode = HashTable[i];
    I think you're getting a null 'CurrentNode' object from this. Add a print statement after that line to verify.
    Last edited by BinaryDigit09; October 20th, 2017 at 01:14 PM. Reason: Forum commit fail

Similar Threads

  1. [SOLVED] Need help desperately: "non-static variable this cannot be referenced from a static context"
    By mikbferguson in forum What's Wrong With My Code?
    Replies: 1
    Last Post: October 2nd, 2017, 08:27 PM
  2. Desperately need help for Uni Assignment. Willing to pay.
    By DJDidymo in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 2nd, 2013, 12:15 AM
  3. NullPointerException?
    By NTWolf1220 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 5th, 2013, 11:46 AM
  4. Help Desperately needed...
    By SBOSlayer in forum Java Theory & Questions
    Replies: 3
    Last Post: November 30th, 2010, 04:10 PM
  5. Desperately in need of help
    By Idy in forum Web Frameworks
    Replies: 0
    Last Post: January 17th, 2010, 02:00 PM