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

Thread: having trouble getting full average and splitting a LinkedList

  1. #1
    Member
    Join Date
    Jun 2012
    Posts
    59
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default having trouble getting full average and splitting a LinkedList

    I'm working with on a LinkedList assignment, however I've written the methods for splitting the list into two equal lists, but when I apply the average it only applies it to the first half of the list. When I try to calculate the average before I split the list, it gives me a null error, but I know I wrote the method correct because it works if I calculate the average after.

    Here is my code.

    import java.util.Random;
     
    public class TestLinkedList{
     
     
    	public static void main(String[] args){
    		UnorderedLinkedList list = new UnorderedLinkedList();
    		int sum=0;
    		Random rand = new Random();
    		for(int i = 0; i<59; i++){
    			int randomNum = rand.nextInt(100)+1;
    			sum = sum + randomNum;
    			list.insertLast(new IntElement(randomNum));
     
    		}
    	System.out.println("Printing the list.");
    		list.print();
     
    		System.out.println("Deleting the first node.");
    		list.deleteFront();
    		list.print();
     
    		System.out.println("Deleting the last node.");
    		list.deleteLast();
    		list.print();
     
    		System.out.println("Inserting node into the front with a number of 68.");
    		list.insertFirst(new IntElement(68));
    		list.print();
     
    		System.out.println("Inserting node into the back with a number of 75.");
    		list.insertLast(new IntElement(75));
    		list.print();
     
     
     
     
    		System.out.println("Now splitting the list into to two equal lists.");
    		list.splitMid(list);
    		list.print(); //shows the first half of the list
     
    			System.out.println("The average is " + list.average());
    		System.out.println(sum/59);
    		System.out.println();
     
    	}
    }

    public abstract class LinkedList{
     
     
    	protected class LinkedListNode{   // inner class node definition
    		protected DataElement info;
    		protected LinkedListNode link;
    	}
     
    	protected LinkedListNode first; //variable to store the address of the first node of the list
    	protected LinkedListNode last;  // variable to store the address of the last node of the list
     
    	protected int count; //variable to store the number of nodes in the list
     
    	//default constructor
    	//initializes the list to an empty state.
    	//postcondition: first = null, last = null, count = 0
     
    	public LinkedList(){
    		first = null;  //
    		last = null;  //empty list
    		count = 0;   //
    	}
     
    	public LinkedList(LinkedList list)
        {
             copy(list);
        }
     
        private void copy(LinkedList list)
        {
            LinkedListNode pointer;
            LinkedListNode newNode;
     
            if(list.first == null)
            {
                first = null;
                last = null;
                count = 0;
            }
            else
            {
                count = list.count;
                pointer = list.first;
                first = new LinkedListNode();
                first.info = pointer.info.getCopy();
                first.link = null;
                last = first;
                pointer = pointer.link;
     
                while(pointer != null)
                {
                    newNode = new LinkedListNode();
                    newNode.info = pointer.info.getCopy();
                    newNode.link = null;
                    last.link = newNode;
                    last = newNode;
                    pointer = pointer.link;
                }
            }
        }
     
     
     
    	//method to determine whether the list is empty
    	//postcondition: returns true if the list is empty; false otherwise
     
     
    	public boolean isEmptyList(){
    		return (count == 0);
    	}
     
     
     
    	//method to initialize the list to an empty state
    	//postcondition: first = null, last = null, count = 0
     
    	public void initializeList(){
    		first = null;
    		last = null;
    		count = 0;
    	}
     
     
    	//method to output the data contained in each node
     
    	public void print(){
     
    	if(count == 0){
    		System.out.println("Cannot print an empty list.");
    	}
    	else{
     
    			LinkedListNode pointer = new LinkedListNode();
    		pointer = first;
    		while(pointer != null){
     
     
    		System.out.println(pointer.info.toString());
    		pointer=pointer.link;
    		}
     
    	}
    	System.out.println();
    	}
     
     
    	//method to return the number of nodes in the list.
    	//postcondition: the value of count is returned
     
    	public int length(){
    		return count;
    	}
     
    	//method to return a reference of the object 
    	//containing the data of the first node of the list
    	//precondition: the list must exist and must not be empty.
    	//postcondition: the reference of the object that contains
    	//the info of the first node is returned
     
    	public DataElement front(){
     
     
    				return first.info.getCopy();
    		}
     
     
    	//Method to return a reference of object containing
            //the data of the last node of the list.
            //Precondition: The list must exist and must not be empty.
            //Postcondition: The reference of the object that
            //contains the info of the last node
            //is returned.
        public DataElement back(){
        	return last.info.getCopy();
        }
     
        //Method to insert newItem in the list.
            //Postcondition: first points to the new list
            //               and newItem is inserted at the
            //               beginning of the list. Also,
            //               last points to the last node and
            //               count is incremented by 1.
        public void insertFirst(DataElement newItem){
        	LinkedListNode newNode = new LinkedListNode();
        newNode.info = newItem.getCopy();
        newNode.link = first;
        first = newNode;
     
        if(last == null){
     
        last = newNode;
        count++;
        }
     
     
        }
     
        //Method to insert newItem at the end of the list.
            //Postcondition: first points to the new list and
            //newItem is inserted at the end
            //of the list. Also, last points to
            //the last node and
            //count is incremented by 1.
        public void insertLast(DataElement newItem){
     
     LinkedListNode newNode = new LinkedListNode();   
        	newNode.info = newItem.getCopy();
        	newNode.link = null;
        	if(first == null){
        		first = newNode;
        		last = newNode;
        	}
        	else{
     
        	last.link = newNode;
        	last = newNode;
        	count++;
        	}
        }
     
        		public void deleteFront()
        {
            if(first.link != null) 
            {
                first = first.link;
                count--;
            }
            else
            {
                first = null;
                last = null;
                count = 0;
            }
        }
     
        public void deleteLast()
        {
            LinkedListNode pointer = first;
            if(pointer.link == null)
            {
                first = null;
                last = null;
                count = 0;
            }
            else 
            {
                while(pointer.link.link != null) pointer = pointer.link;
                pointer.link = null;
                last = pointer;
                count--;
            }
        }
     
         public void splitMid(LinkedList list)
        {
            int stopPoint = list.count / 2;
            LinkedListNode pointer = null;
            pointer = list.first.link;
            for(int i = 0; i < stopPoint; i++)
            {
                pointer = pointer.link;
            }
            LinkedListNode secondFirst = pointer.link;
     
            pointer.link.link = null;
     
        }
     
     
            public double average(){
        			int sum=0;
        			LinkedListNode pointer = new LinkedListNode();
     
        			while(pointer!=null){
     
        			pointer = first;
        			pointer.link = first.link;
        			System.out.println("Method avg pointer = " + pointer + " first = " + first);
        			IntElement temp = (IntElement)pointer.info.getCopy();
        			sum = sum + temp.getNum();
        			first = pointer.link;
        			if(pointer.link.link == null)
        			{
        				break;
        			}
        			else{
     
     
        			first.link = pointer.link.link;
        			System.out.println(sum);
        			}
     
        			}
        		double average = (sum/59);
        		return average;
     
        		}
     
     
        //Method to determine whether searchItem is in the list.
        //Postcondition: Returns true if searchItem is found
        //in the list; false otherwise.
        public abstract boolean search(DataElement searchItem);	
     
    		//Method to delete deleteItem from the list.
            //Postcondition: If found, the node containing
            //deleteItem is deleted from the
            //list. Also first points to the first
            //node, last points to the last
            //node of the updated list, and count
            //is decremented by 1.
        public abstract void deleteNode(DataElement deleteItem);
     
     
     
     
      	}

    public class UnorderedLinkedList extends LinkedList{
     
     
    	public UnorderedLinkedList(){
    		super();
    	}
     
    	public UnorderedLinkedList(UnorderedLinkedList list){
    		super(list);
    	}
     
    	//Method to determine whether searchItem is in the list.
            //Postcondition: Returns true if searchItem is found
            //in the list; false otherwise.
        public boolean search(DataElement searchItem){
     
        LinkedListNode pointer = new LinkedListNode();
        pointer = first;
        boolean foundData = false;
     
        while(pointer != null && !foundData){
        	if(pointer.info.equals(searchItem) == true){
        		foundData = true;
        	}
        	else{
        		pointer = pointer.link;
        	}
     
        }
        return foundData;	
     
        }
     
     
        //Method to delete deleteItem from the list.
            //Postcondition: If found, the node containing
            //deleteItem is deleted from the
            //list. Also first points to the first
            //node, last points to the last
            //node of the updated list, and count
            //is decremented by 1.
        public void deleteNode(DataElement deleteItem){
     
        	if(count == 0)
        		System.out.println("The list is empty.");
        		else{
        			if(first.info.equals(deleteItem) == true)
        			{
        				if(first.link == null){
        					first = null;
        					last = null;
        					count = 0;
        				}
        				else{
        					first = first.link;
        					count--;
        					if(count == 1){
        						first.link = null;
        						last = first;
        					}
        				}
        			}
     
        			else{
        			LinkedListNode pointer = new LinkedListNode();
        			pointer = first;
     
        			while(pointer.info.equals(deleteItem) != true){
        				pointer = pointer.link;
        				pointer.link = pointer.link.link; //inception
     
        				if(pointer.link == null){
        					last = pointer;
        					count--;
        				}
     
        			}	
     
     
        			}
        			}
     
     
     
     
        }
     
    }


    public abstract class DataElement{
     
    	public abstract boolean equals(DataElement otherElement);
     
    	public abstract int compareTo(DataElement otherElement);
     
    	public abstract void makeCopy(DataElement otherElement);
     
    	public abstract DataElement getCopy();
     
     
    }

    public class IntElement extends DataElement
    {
     
        protected int number;
     
        public IntElement()
        {
            number = 0;
        }
     
        public IntElement(int num)
        {
            number = num;
        }
     
        public IntElement(IntElement obj)
        {
            this.number = obj.getNum();
     
        }
     
        public void setNum(int num)
        {
     
            number = num;
        }
     
        public String toString()
            {
                return Integer.toString(number);
            }
     
        public int getNum()
        {
     
            return number;
        }
     
        public boolean equals(DataElement obj)
        {
     
    		if (obj == null) return false;
    		if (getClass() != obj.getClass()) return false;
    		IntElement temp = (IntElement)obj;
    		return (number == temp.number); 
        }
     
        public int compareTo(DataElement obj)
    	{
    		IntElement temp = (IntElement)obj;
    		if (number < temp.number) return -1;
    		else if (number > temp.number) return 1;
    		else return 0;
    	}
     
    public void makeCopy(DataElement obj)
    	{
    		IntElement temp = (IntElement)obj;
    		number = temp.number;
    	}
     
    	public DataElement getCopy()
    	{
    		DataElement temp = new IntElement(number);
    		return temp;
    	}
     
    }


    edit: I just figured out by using the constructor I can make a copy of the list. I was trying to copy using LinkedList object when it's abstract instead of creating a Unordered object. My average method is having trouble. It keeps cutting off the last node's number. Why is it doing this? I'm trying to figure out how to fix it.
    import java.util.Random;
     
    public class TestLinkedList{
     
     
    	public static void main(String[] args){
    		UnorderedLinkedList list = new UnorderedLinkedList();
    		int sum=0;
    		Random rand = new Random();
    		for(int i = 0; i<59; i++){
    			int randomNum = rand.nextInt(100)+1;
    			sum = sum + randomNum;
    			list.insertLast(new IntElement(randomNum));
     
    		}
    	System.out.println("Printing the list.");
    		list.print();
     
    		System.out.println("Deleting the first node.");
    		list.deleteFront();
    		list.print();
     
    		System.out.println("Deleting the last node.");
    		list.deleteLast();
    		list.print();
     
    		System.out.println("Inserting node into the front with a number of 68.");
    		list.insertFirst(new IntElement(68));
    		list.print();
     
    		System.out.println("Inserting node into the back with a number of 75.");
    		list.insertLast(new IntElement(75));
    		list.print();
     
    		UnorderedLinkedList copyList = new UnorderedLinkedList(list);
     
    		System.out.println("Now splitting the list into to two equal lists.");
    		list.splitMid(list);
    		list.print(); //shows the first half of the list
     
    				System.out.println("The average is " + copyList.average());
    				System.out.println(sum/59.0);
    		System.out.println();
     
     
     
    	}
    }

    The average is 51.23728813559322
    52.389830508474574
    Last edited by orbin; October 22nd, 2012 at 03:18 PM.


  2. #2
    Member
    Join Date
    Jun 2012
    Posts
    59
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: having trouble getting full average and splitting a LinkedList

    Been racking my brain. I can't figure out now why my average and stdDeviation method aren't working anymore.

    public abstract class LinkedList{
     
     
    	protected class LinkedListNode{   // inner class node definition
    		protected DataElement info;
    		protected LinkedListNode link;
    	}
     
    	protected LinkedListNode first; //variable to store the address of the first node of the list
    	protected LinkedListNode last;  // variable to store the address of the last node of the list
     
    	protected int count; //variable to store the number of nodes in the list
     
    	//default constructor
    	//initializes the list to an empty state.
    	//postcondition: first = null, last = null, count = 0
     
    	public LinkedList(){
    		first = null;  //
    		last = null;  //empty list
    		count = 0;   //
    	}
     
    	public LinkedList(LinkedList list)
        {
             copy(list);
        }
     
        private void copy(LinkedList list)
        {
            LinkedListNode pointer;
            LinkedListNode newNode;
     
            if(list.first == null)
            {
                first = null;
                last = null;
                count = 0;
            }
            else
            {
                count = list.count;
                pointer = list.first;
                first = new LinkedListNode();
                first.info = pointer.info.getCopy();
                first.link = null;
                last = first;
                pointer = pointer.link;
     
                while(pointer != null)
                {
                    newNode = new LinkedListNode();
                    newNode.info = pointer.info.getCopy();
                    newNode.link = null;
                    last.link = newNode;
                    last = newNode;
                    pointer = pointer.link;
                }
            }
        }
     
     
     
    	//method to determine whether the list is empty
    	//postcondition: returns true if the list is empty; false otherwise
     
     
    	public boolean isEmptyList(){
    		return (count == 0);
    	}
     
     
     
    	//method to initialize the list to an empty state
    	//postcondition: first = null, last = null, count = 0
     
    	public void initializeList(){
    		first = null;
    		last = null;
    		count = 0;
    	}
     
     
    	//method to output the data contained in each node
     
    	public void print(){
     
    	if(count == 0){
    		System.out.println("Cannot print an empty list.");
    	}
    	else{
     
    			LinkedListNode pointer = new LinkedListNode();
    		pointer = first;
    		while(pointer != null){
     
     
    		System.out.println(pointer.info.toString());
    		pointer=pointer.link;
    		}
     
    	}
     
    	}
     
     
    	//method to return the number of nodes in the list.
    	//postcondition: the value of count is returned
     
    	public int length(){
    		return count;
    	}
     
    	//method to return a reference of the object 
    	//containing the data of the first node of the list
    	//precondition: the list must exist and must not be empty.
    	//postcondition: the reference of the object that contains
    	//the info of the first node is returned
     
    	public DataElement front(){
     
     
    				return first.info.getCopy();
    		}
     
     
    	//Method to return a reference of object containing
            //the data of the last node of the list.
            //Precondition: The list must exist and must not be empty.
            //Postcondition: The reference of the object that
            //contains the info of the last node
            //is returned.
        public DataElement back(){
        	return last.info.getCopy();
        }
     
        //Method to insert newItem in the list.
            //Postcondition: first points to the new list
            //               and newItem is inserted at the
            //               beginning of the list. Also,
            //               last points to the last node and
            //               count is incremented by 1.
        public void insertFirst(DataElement newItem){
        	LinkedListNode newNode = new LinkedListNode();
        newNode.info = newItem.getCopy();
        newNode.link = first;
        first = newNode;
     
        if(last == null){
     
        last = newNode;
        count++;
        }
     
     
        }
     
        //Method to insert newItem at the end of the list.
            //Postcondition: first points to the new list and
            //newItem is inserted at the end
            //of the list. Also, last points to
            //the last node and
            //count is incremented by 1.
        public void insertLast(DataElement newItem){
     
     LinkedListNode newNode = new LinkedListNode();   
        	newNode.info = newItem.getCopy();
        	newNode.link = null;
        	if(first == null){
        		first = newNode;
        		last = newNode;
        	}
        	else{
     
        	last.link = newNode;
        	last = newNode;
        	count++;
        	}
        }
     
        		public void deleteFront()
        {
            if(first.link != null) 
            {
                first = first.link;
                count--;
            }
            else
            {
                first = null;
                last = null;
                count = 0;
            }
        }
     
        public void deleteLast()
        {
            LinkedListNode pointer = first;
            if(pointer.link == null)
            {
                first = null;
                last = null;
                count = 0;
            }
            else 
            {
                while(pointer.link.link != null) pointer = pointer.link;
                pointer.link = null;
                last = pointer;
                count--;
            }
        }
     
         public void splitMid(LinkedList list)
        {
            int stopPoint = list.count / 2;
            LinkedListNode pointer = null;
            pointer = list.first.link;
            for(int i = 0; i < stopPoint; i++)
            {
                pointer = pointer.link;
            }
            LinkedListNode secondFirst = pointer.link;
     
            pointer.link.link = null;
     
        }
     
     
            public double average(){
        			double sum=0;
        			LinkedListNode pointer = new LinkedListNode();
     
        			while(pointer != null){
     
        			pointer = first;
        			pointer.link = first.link;
        			IntElement temp = (IntElement)pointer.info.getCopy();
        			sum = sum + temp.getNum();
        			System.out.println("temp num: " + temp.getNum());
        			first = pointer.link; 
        				if(pointer.link.link != null){
     
        			first.link = pointer.link.link;
        				}
        				else{
        				pointer = first;
        				IntElement temp2 = (IntElement)pointer.info.getCopy();
        			sum = sum + temp.getNum();
        				break;
        				}
        			}
     
        		double average = (sum/59.0);
        		return average;
     
        		}
     
        		public double stdDev(double avg){
        			double stdAvg = avg;
        			double variance = 0;
        			LinkedListNode pointer = new LinkedListNode();
     
        			while(pointer!= null){
     
        				pointer = first;
        				pointer.link = first.link;
        				IntElement temp = (IntElement)pointer.info.getCopy();
        				variance = variance + ((temp.getNum() - stdAvg)*(temp.getNum() - stdAvg));
     
        				first = pointer.link;
        				if(pointer.link.link != null){
     
        				first.link = pointer.link.link;
        				}
        				else{
        					pointer = first;
        					IntElement temp2 = (IntElement)pointer.info.getCopy();
        					variance = variance + ((temp.getNum() - stdAvg)*(temp.getNum() - stdAvg));
     
     
        				}
        			}
        			return (Math.sqrt(variance/59));
        		}
     
     
        //Method to determine whether searchItem is in the list.
        //Postcondition: Returns true if searchItem is found
        //in the list; false otherwise.
        public abstract boolean search(DataElement searchItem);	
     
    		//Method to delete deleteItem from the list.
            //Postcondition: If found, the node containing
            //deleteItem is deleted from the
            //list. Also first points to the first
            //node, last points to the last
            //node of the updated list, and count
            //is decremented by 1.
        public abstract void deleteNode(DataElement deleteItem);
     
     
     
     
      	}

    import java.util.Random;
     
    public class TestLinkedList{
     
     
    	public static void main(String[] args){
    		UnorderedLinkedList list = new UnorderedLinkedList();
    		Random rand = new Random();
    		for(int i = 0; i<=59; i++){
    			int randomNum = rand.nextInt(100)+1;
    			list.insertLast(new IntElement(randomNum));
     
    		}
     
     
     
    		UnorderedLinkedList copyList = new UnorderedLinkedList(list); //a copy of the linked list to use
     
    			System.out.println("The average is: " + list.average());
     
    				System.out.println("The Standard Deviation is: " + list.stdDev(list.average()));
     
    	System.out.println("Printing the list.");
    		list.print();
     
    		System.out.println("Deleting the first node.");
    		list.deleteFront();
    		list.print();
     
    		System.out.println("Deleting the last node.");
    		list.deleteLast();
    		list.print();
     
    		System.out.println("Inserting node into the front with a number of 68.");
    		list.insertFirst(new IntElement(68));
    		list.print();
     
    		System.out.println("Inserting node into the back with a number of 75.");
    		list.insertLast(new IntElement(75));
    		list.print();
     
    		System.out.println("Now splitting the list into to two equal lists.");
    		list.splitMid(list);
    		list.print(); //shows the first half of the list
     
     
     
     
    	}
    }

    temp num: 41
    temp num: 4
    temp num: 2
    temp num: 1
    The average is: 49.50847457627118
    temp num: 41
    Exception in thread "main" java.lang.NullPointerException
        at LinkedList.average(LinkedList.java:242)
        at TestLinkedList.main(TestLinkedList.java:21)
     
    Process completed.

  3. #3
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: having trouble getting full average and splitting a LinkedList

    It is easier to find problems and give advice if you provide a detailed explanation about what the code is doing, what you want it to do, and any error messages you may have. To say some number of things "aren't working anymore" is not very descriptive. Though it does suggest these things did work before. Which suggests there may be some code recently changed and caused them to stop working. But that is the best I have to offer without more to go on, or spending hours racking my brain too.

Similar Threads

  1. Having trouble splitting a text file into multiple arrays.
    By orbin in forum What's Wrong With My Code?
    Replies: 21
    Last Post: June 19th, 2012, 06:27 PM
  2. Splitting String
    By JuLiAnc in forum What's Wrong With My Code?
    Replies: 3
    Last Post: December 17th, 2011, 10:23 AM
  3. Trouble wil XML Encoder/Decoder using linkedlist<parameter>
    By javanoobb in forum What's Wrong With My Code?
    Replies: 0
    Last Post: October 15th, 2011, 06:59 PM
  4. Splitting an Array?
    By ThatGuy1234 in forum Java Theory & Questions
    Replies: 1
    Last Post: January 19th, 2011, 08:20 AM
  5. Splitting File into Array
    By Scottj996 in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: March 3rd, 2010, 11:48 AM