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 14 of 14

Thread: Null pointers

  1. #1
    Junior Member
    Join Date
    Oct 2010
    Posts
    11
    Thanks
    3
    Thanked 1 Time in 1 Post

    Default Null pointers

    I'm getting either a null pointer, or some other kind of problem. So far, in this program, I only have the multiply function completed to the point where it ought to work. However, either in my toString method or my function call, i think I've got something wrong. The problem may be elsewhere, too, but I think it's just there. You have to enter a value first, then you select multiply on the case statement. I have to do this part first so I can test to make sure the code I've got works. Without further ado:

    My main:
    import java.util.Scanner;
     
    public class main 
    {
        public static void main(String [] args)
        {
            Scanner scan = new Scanner(System.in);
            int x = 0;
            String choice = null;
            String entry = null;
            String answer = null;
            Number n = new Number();
            Number m = new Number();
            while (x != 1)
            {
                /* This is a simple menu, which feeds into a switch statement. The switch
                 * has to be done with a literal or an integer, so we first parse the 
                 * string given by the scanner to just the character at position 0 (the
                 * first spot). It switches accordingly.
                 */
                System.out.print("Enter a value: e      Add a value: a\n" +
                                 "Subtract: s           Multiply: m\n" +
                                 "Reverse sign: r       Clear: c\n" +
                                 "Quit: q\n -->"
                                 );
                choice = scan.next();
                char choice1 = choice.charAt(0);
     
                switch(choice1)
                {
                    case 'e':
                        System.out.print("Please enter a number:  ");
                        entry = scan.next();
                        n = new Number(entry);
                        break;
                    case 'a':
     
                        break;
                    case 's':
     
                        break;
                    case 'm':
                        System.out.print("Please enter a number:  ");
                        entry = scan.next();
                        m = new Number(entry);
                        n = m.multiply(n);
                        answer = n.toString();
                        System.out.println("" + answer);
                        break;
                    case 'r':
                        n.reverseSign();
                        break;
                    case 'c':
                        n = new Number();
                        break;
                    case 'q':
                        x = 1;
                        break;
                    default:
                        System.out.println("Invalid selection, please try again");
     
                }
            }
        }
    }

    My Number Class
    public class Number 
    {
        private Node low, high;
        private int digitCount = 0;
        private int decimalPlaces = 0;
        private boolean negative = false;
     
     
         public Number()// constructor
         {
             low = null;
             high = null;
         }
     
         // while I'm pretty sure that to enter a value, you don't need to worry about this
         // this constructor is needed when you are subtracting or doing any other elementary
         // operation. without it, it wouldn't be able to make it a linked list.
         public Number(String str)
         {
             accept(str);
         }
         public void accept(String str)
         {
             int length = str.length();
             // in case of a decimal number, we have to make sure we're ready for it. we do that by parsing a float, then 
             // later casting it to an integer. we use this only to see if x is greater than 0.
             int x = (int)Float.parseFloat(str);
     
             // if the integer is less than 0, it is negative
             // and we flip the sign, else we do nothing
             if (x < 0)
             {
                 System.out.println("" + x);
                 reverseSign();
             }
     
     
             for(int i = 0; i < length; i++)
             {
     
                 char place = str.charAt(i);
                 /* I'm checking to see if the character at the place is a 
                  * digit. If it is, I cast it as an integer, which it is, 
                  * and send it to the insertNode method, which adds it as a node.
                  */
                 if(Character.isDigit(place))
                 {
                     insertNodeBack((int)place);
                 }
                 else
                     if(place == '.')
                     {
                         decimalPlaces = length - i;
                     }
                     else 
                     {
                         //Do nothing, it's a negative sign. The loop will increment.
                     }
     
             }
         }
         public Number add(Number n)
         {
            return n;
             //. Returns a Number which represents "this + n".
         }
         public Number subtract(Number n)
         {
     
            return n;
             //. Returns a Number which represents "this - n".
         }
         public Number multiply(Number n)
         {
     
             int newDigit;
             Number product = new Number();
             Node npointer = n.high;
             while (npointer != null)
             {
                 Number partialProduct = new Number();
                 int carry = 0;
                 Node current = this.low;
                 while(current != null)
                 {
                     newDigit = npointer.getValue() * current.getValue();
                     carry = newDigit / 10;
                     newDigit = newDigit %10;
     
                     partialProduct.digitCount++;
                     current = current.previous;
                     if(carry != 0)
                     {
                         partialProduct.insertNodeFront(carry);
                         partialProduct.digitCount++;
                     }
                     product.insertNodeBack(0);
                     product.digitCount++;
                     product = product.addAbsolute(partialProduct);
                     npointer = npointer.next;
                     product.decimalPlaces = this.decimalPlaces + n.decimalPlaces;
                 }
             }
     
             return product;
         }
         public void reverseSign() //This method changes the sign of the number represented by the linked list.
         {
             if (negative == true)
                 negative = false;
             else
                 negative = true;
     
         }
     
         //Returns a String representation of the Number (so it can be displayed by System.out.print()).
         public String toString()
         {
             int beforeDecimal = digitCount - decimalPlaces, digit;
             Node current = this.high;
             String solution = null;
             if(negative)
                 solution += '-';
             for(int i = 0; i < beforeDecimal; i++)
             {
                 digit = current.getValue();
                 solution += digit;
                 current = current.next;
             }
             solution += '.';
             for(int i = digitCount - beforeDecimal; i < digitCount; i++)
             {
                 digit = current.getValue();
                 solution += digit;
                 current = current.next;
             }
            return solution;
         }
     
         /* Because of the way I've set up the linked list, the first piece added will always be the highest
          * order node. Thus, this method is the same to just adding a last node every time. When this method is called
          * we already know if we have a negative or not, from the parsing done in accept. If the list isn't empty, we simply 
          * set the pointer for the low node to the node we create.
          */
        private void insertNodeBack(int value)
         {
            Node newNode = new Node(value); 
            if (isEmpty()) 
                this.high = newNode; 
            else 
            {
                low.next = newNode; 
                newNode.previous = low; 
            }
            this.low = newNode;
         }
     
        /*This method tells if the list is empty or not.*/
        private boolean isEmpty()
        {
            return high == null;
        }
     
        private Number addAbsolute(Number n)
        {
            Number sum = new Number();
            int carry = 0;
            int added;
            Node thisPointer = this.low;
            Node nPointer = n.low;
            while (thisPointer != null)
            {
                added = thisPointer.getValue();// + nPointer.getValue();
                carry = added / 10;
                added = added %10;
                sum.digitCount++;
                thisPointer = thisPointer.previous;
                nPointer = nPointer.previous;
                if(carry != 0)
                {
                    sum.insertNodeFront(carry);
                    sum.digitCount++;
                }
                //set ap value for decimal places in sum
            }
            return sum;
     
        }
     
        /* Well, because of the functions we use, we have to properly be able to add to the head of the list
         * instead of just the back. To do this, we'll do pretty much the same thing as we did on insertNodeTail,
         * however, we'll insert to the front. 
         */
        private void insertNodeFront(int value)
         {
            Node newNode = new Node(value); 
            if (isEmpty()) 
                low = newNode; //its both high and low if list is empty
            else 
            {
                high.previous = newNode; 
                newNode.next = high; // reassign the pointers for existing high
            }
            high = newNode; //override existing high
         }
        private int compareToAbsolute(Number n)
        {
            return decimalPlaces;
     
        }
     
        private Number subtractAbsolute(Number n)
        {
            Number difference = new Number();
            int borrow = 0, newDigit;
            Node thisPointer = this.low;
            Node nPointer = n.low;
            while (thisPointer != null)
            {
                newDigit = thisPointer.getValue() - nPointer.getValue();
                if (newDigit < 0)
                {
                    newDigit +=10;
                    borrow = 1;
                }
                else
                {
                    borrow = 0;
                }
     
                difference.insertNodeFront(newDigit);
                difference.digitCount++;
                //set app value for dec. places
            }
            return difference;
     
        }
    }

    And my Node class
    public class Node 
    {
     
        public int data;
        public Node next;
        public Node previous;
     
        public Node(int value)
        {
            data = value;
        }
     
        public int getValue()
        {
            return data;
        }    
    }

    Any help is greatly appreciated. It's my shot at what is supposed to be a calculator capable of the functions provided.


  2. #2
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Null pointers

    Well, it's probably from setting so many things to null. Some values may not have been set to something else, leaving them still null.
    As a rule, though I never follow it very much myself, but I'm learning to, try to make all your variables in Node private unless you need them to be modified directly outside Node.

    PHP Code:
    public Number add(Number n)
         {
            return 
    n;
             
    //. Returns a Number which represents "this + n".
    // well what you're doing is returning n, not this + n.  


         
    }
         public 
    Number subtract(Number n)
         {
             
            return 
    n;
             
    //. Returns a Number which represents "this - n".
         

    PHP Code:
    [CODE]= new Number(entry);
    [/
    CODE
    You already did m = new Number(); earlier
    Last edited by javapenguin; October 6th, 2010 at 03:45 PM.

  3. #3
    Junior Member
    Join Date
    Oct 2010
    Posts
    11
    Thanks
    3
    Thanked 1 Time in 1 Post

    Default Re: Null pointers

    I've been looking more closely at what's been happening inside the program, and it's a bit bizarre. I'll try setting them to private in a second, and providing getters and setters for them, I just didn't think it'd make a difference. In my code, I tried seeing what was passed to the method insertToBack, and it's a proper value. However, what gets inserted in the node is like 51, or a number in that ballpark. I have no idea why, though.

  4. #4
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Null pointers

    Quote Originally Posted by Jared View Post
    I've been looking more closely at what's been happening inside the program, and it's a bit bizarre. I'll try setting them to private in a second, and providing getters and setters for them, I just didn't think it'd make a difference. In my code, I tried seeing what was passed to the method insertToBack, and it's a proper value. However, what gets inserted in the node is like 51, or a number in that ballpark. I have no idea why, though.
    What are you hoping for? What type of number? Is it a 1 or 5 or a 15?

    If it's a 1 or a 5, maybe it's putting two values like 5 and 1 together to get 51.

  5. #5
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Null pointers

    String solution = null;
    if(negative)
    solution += '-';

    negative == what?

    I'm not sure if you can use += with a String. Are you meaning to add it to a null String? Maybe solution can't be null to start out with. if you're adding something to the String and want to add that value to the end of the string, you do this:

    solution.concat("-");
    Also, using one set of quotes, like this 'x', means character or char usually.

    Try initially making solution = ""

    String solution = "";

    Also, this.high would be null, as I can't find where you changed it from that.
    Last edited by javapenguin; October 6th, 2010 at 04:26 PM.

  6. The Following User Says Thank You to javapenguin For This Useful Post:

    Jared (October 6th, 2010)

  7. #6
    Junior Member
    Join Date
    Oct 2010
    Posts
    11
    Thanks
    3
    Thanked 1 Time in 1 Post

    Default Re: Null pointers

    Yeah, I've sinced fixed all of that in my code, however, my biggest problem lies in the accept method now, specifically where the value is passed to the method insertNodeBack. For some reason, the value is getting mangled when it's added to the Node.I'm using some code to test it out
     private void insertNodeBack(int value)
         {
            System.out.println(value);
            Node newNode = new Node(value);
            if (isEmpty())
                this.high = newNode;
            else
            {
                low.setNext(newNode);
                newNode.setPrevious(low);
            }
            this.low = newNode;
                    System.out.println(low.getValue());
         }

    The above is where the problem lies, although I'm completely oblivious as to why. As you can see when you replace the method with the above, the value going in is whatever the first number is when you run it, however, it goes to something around 50 when it comes out. I really appreciate your feedback so far. This code, I feel, is paramount to testing the subtraction and addition methods, as it requires no lining up of decimal places, and thus shows flaws in the underlying code. Further, here is my updated Node class:

    package javaapplication1;
     
    public class Node
    {
     
        private int data = 0;
        private Node next;
        private Node previous;
     
        public Node(int value)
        {
            data = value;
        }
     
        public int getValue()
        {
            return data;
        }
     
        public void setPrevious(Node previous)
        {
            this.previous = previous;
        }
     
        public Node getPrevious()
        {
            return previous;
        }
     
        public void setNext(Node next)
        {
            this.next = next;
        }
     
        public Node getNext()
        {
            return next;
        }
    }

    I've set everything to private, and the constructor, it would seem, simply sets the value of the node to whatever integer is given. I dont understand where it changes, or why.

  8. #7
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Null pointers

    Quote Originally Posted by Jared View Post
    Yeah, I've sinced fixed all of that in my code, however, my biggest problem lies in the accept method now, specifically where the value is passed to the method insertNodeBack. For some reason, the value is getting mangled when it's added to the Node.I'm using some code to test it out
     private void insertNodeBack(int value)
         {
            System.out.println(value);
            Node newNode = new Node(value);
            if (isEmpty())
                this.high = newNode;
            else
            {
                low.setNext(newNode);
                newNode.setPrevious(low);
            }
            this.low = newNode;
                    System.out.println(low.getValue());
         }

    The above is where the problem lies, although I'm completely oblivious as to why. As you can see when you replace the method with the above, the value going in is whatever the first number is when you run it, however, it goes to something around 50 when it comes out. I really appreciate your feedback so far. This code, I feel, is paramount to testing the subtraction and addition methods, as it requires no lining up of decimal places, and thus shows flaws in the underlying code. Further, here is my updated Node class:

    package javaapplication1;
     
    public class Node
    {
     
        private int data = 0;
        private Node next;
        private Node previous;
     
        public Node(int value)
        {
            data = value;
        }
     
        public int getValue()
        {
            return data;
        }
     
        public void setPrevious(Node previous)
        {
            this.previous = previous;
        }
     
        public Node getPrevious()
        {
            return previous;
        }
     
        public void setNext(Node next)
        {
            this.next = next;
        }
     
        public Node getNext()
        {
            return next;
        }
    }

    I've set everything to private, and the constructor, it would seem, simply sets the value of the node to whatever integer is given. I dont understand where it changes, or why.
    private void insertNodeBack(int value)
         {
            System.out.println(value);
            Node newNode = new Node(value);
            if (isEmpty() == true or false. pick one)
                this.high = newNode;
            else
            {
                low.setNext(newNode); // what value does low have at this point?  
                newNode.setPrevious(low);
            }
            this.low = newNode;
                    System.out.println(low.getValue());
         }

    It seems the error may be in the Number class.

    Well, accept() and the constructor both take as a parameter the String str.

    If you do this

    Number num = new Number("Bla Bla Bla");

    and accept("Yak yak yak");

    even though you have str in both cases, they are not equal.

    That may not be the problem, just thought it odd.

    I mean

    Number (String str)
    // the vallue of str passed is "Bla bla bla".
    accept(str); // this will use the str value "Bla bla bla" as parameter, not "Yak yak yak".
    }

    accept(String str)
    {
    // the str value is "Yak yak yak".
    }

    Hmmmm, could this be the problem?:

    low = null;
             high = null;

    Also, your add and subtract, and maybe even add absolute, methods only return the number passed to it.

    Are you trying to get

    add(int x)
    {
    int n = this.something + x;
    return(n);
    }
    Last edited by javapenguin; October 6th, 2010 at 05:10 PM.

  9. #8
    Junior Member
    Join Date
    Oct 2010
    Posts
    11
    Thanks
    3
    Thanked 1 Time in 1 Post

    Default Re: Null pointers

    What the program aims to do is create a doubly linked list that holds a single digit of a number in each of the nodes. This doubly linked list is then aligned with the other doubly linked list to do addition and subtraction. Since I can't test to see if my code lines it up properly until i have the multiplication down pat (because multiplication is independent of digits needing to be lined up), I've been working on getting that fixed. The problem I'm having is two-fold, though. Part of my problem is that I'm getting a bizarre number as my node for the data. The other problem is I'm unsure of the way the program itself works. Although I'm confident I've got the majority of the code correct (for the parts I've done), I'm unsure of how the interaction between the doubly linked lists works. I know that each time I pass in a string to the constructor, it rips it apart and makes it into the doubly linked list (albeit incorrectly, due to the issues I've mentioned with the values being off). I don't know what is persistant, if anything, in the classes. I think that's where my null pointer issue arises. I'm kind of banking on the fact that when i send in one for multiplication, we have the linked list prior to that in memory, and the other is parsed upon being sent in. I know this to be incorrect though. I feel like i'm kind of rambling at this point, to be honest. I do, however, know that the values are off, and that the problem occurs somewhere in either the node class, or in the insertToBack method. I really appreciate all the hlep so far.

  10. #9
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Smile Re: Null pointers

    I was wondering if you were doing some kind of Linked List, as I just covered them in class lately. I still don't know much about them. However, I recognized the Node class. However, normally I've seen Node as an inner class inside the generic Linked List class. And I've seen that Node that was private class. That's what my professor said to make it, if you're making it an inner class.


    Here's the link list we did in class, though it's a singly linked list
    public class SinglyLinkedList 
    {
    	private class Node
    	{
    		private int data;
    		private Node next;
     
    		public Node(int data,Node next)
    		{
    			this.data = data;
    			this.next = next;
    		}
     
    		public int getData()
    		{
    			return data;
    		}
     
    		public Node getNext()
    		{
    			return next;
    		}
     
    		public void setNext(Node next)
    		{
    			this.next = next;
    		}		
    	}
     
    	private Node head;//head of the linked list
    	private int size;
     
    	public SinglyLinkedList()
    	{
    		head = null;
    		size = 0;
    	}
     
    	public void addFirst(int data)
    	{
    		Node newnode = new Node(data,head);
     
    		head = newnode;
    		size++;
    	}
     
    	public void removeFirst()
    	{
    		Node current = head;
     
    		head = head.getNext(); //move head to the next element
    		current.setNext(null);
    	}
     
    	public void addLast(int data)
    	{
    		Node current;
     
    		if (head==null)
    		{
    			addFirst(data);
    			return;
    		}
     
    		current = head;
     
    		while (current.getNext()!=null)
    			current = current.getNext();
     
    		Node newnode = new Node(data,null);
     
    		current.setNext(newnode);
    		size++;
     
    	}
     
    	public void add(int index,int data)
    	{
    		int i;
     
    		if (index>size)
    			return;
     
    		if (head==null)
    		{
    			addFirst(data);
    			return;
    		}
     
    		//step 1
    		Node current;
     
    		current = head;
     
    		for (i=0;i<index-1;i++)
    		{
    			current = current.getNext();
    		}
     
    		//current now refers to object immediately before new node
     
    		//step 2
    		Node newnode = new Node(data,current.getNext());
     
    		//step 3
     
    		current.setNext(newnode);
    		size++;
    	}		
    }

    Also, I found a potential problem in your code, unless you fixed it.
      insertNodeBack((int)place);

    why are you type casting a char to be an int?

    Oh, you found that, oh never mind then.
    Last edited by javapenguin; October 6th, 2010 at 06:40 PM.

  11. #10
    Junior Member
    Join Date
    Oct 2010
    Posts
    11
    Thanks
    3
    Thanked 1 Time in 1 Post

    Default Re: Null pointers

    I figured it out, it's the way I casted the variable that caused it to get all messed up. Now I can move on! I should elaborate in case anyone else has this problem. It was returning the ASCII value instead of the true value, which is what happens when a character is casted to an integer. As I was unaware of this, it really screwed me up. I'll post again when I figure out how to properly cast it.
    Last edited by Jared; October 6th, 2010 at 06:36 PM.

  12. #11
    Junior Member
    Join Date
    Oct 2010
    Posts
    11
    Thanks
    3
    Thanked 1 Time in 1 Post

    Default Re: Null pointers

    I decided to take the easy way out and subtract the 48 from the number, then insert it in the node.

  13. #12
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Null pointers

    Quote Originally Posted by Jared View Post
    I decided to take the easy way out and subtract the 48 from the number, then insert it in the node.
    Don't do that. Read the API for Character for a static method that returns the numeric value (hint, hint) of a char.

    And if you must approach this the wrong way, at least subtract '0' and not 48, as that makes the intent of the code immediately visible.

    db

  14. The Following User Says Thank You to Darryl.Burke For This Useful Post:

    Jared (October 7th, 2010)

  15. #13
    Junior Member
    Join Date
    Oct 2010
    Posts
    11
    Thanks
    3
    Thanked 1 Time in 1 Post

    Default Re: Null pointers

    Thanks, just looked it up. I only did a cursory look at it before deciding on the other solution earlier. Mind saying why it's better to use getNumericValue? I understand that it's built for doing that, but the way I parse the number in the first place makes it so that I won't get anything other than an integer from 0-9 as the value that I pass. Is it just bad practice?

  16. #14
    Junior Member
    Join Date
    Oct 2010
    Posts
    11
    Thanks
    3
    Thanked 1 Time in 1 Post

    Default Re: Null pointers

    Ok, so I need help for the, hopefully, final time. I don't know how to make the Doubly Linked List I make persistent. What I mean by this is I don' tknow how to keep it there so I can access it later, and thus, while i'm sure the lists are formed correctly, I can't use them anyways.

Similar Threads

  1. Returning Null
    By Woody619 in forum What's Wrong With My Code?
    Replies: 11
    Last Post: July 22nd, 2010, 12:53 PM
  2. [SOLVED] Null Pointer Exception
    By musasabi in forum What's Wrong With My Code?
    Replies: 2
    Last Post: May 11th, 2010, 09:25 PM
  3. !=null
    By ss7 in forum Java Theory & Questions
    Replies: 11
    Last Post: October 31st, 2009, 02:48 PM
  4. NullPointerException:null problem
    By derky in forum Exceptions
    Replies: 8
    Last Post: September 18th, 2009, 03:06 PM
  5. [SOLVED] Problem in generating Fibonacci sequence in java
    By big_c in forum Algorithms & Recursion
    Replies: 2
    Last Post: April 24th, 2009, 08:52 AM