Results 1 to 19 of 19
Like Tree1Likes
  • 1 Post By Junky

Thread: Having trouble printing the LinkedList correctly..

  1. #1
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default Having trouble printing the LinkedList correctly..

    Here is my code

    Java Code:
    public class ReadTestHarness
    {
    	// no argument constructor
        public ReadTestHarness()
        {
        }
        // end empty ReadTestHarness constructor
    
        /**
         *method main instantiates ReadStudentGPA object then proceeds to call its methods
         *within the class.
         */
        public static void main(String[] args)
        {
        	ReadStudentGPA test = new ReadStudentGPA();//instantiation of ReadStudentGPA object
    
        	test.openFile();//Calling the openFile method in order to open the file.
        	test.readGpaRecord();//Calling the readGpaRecord method in order to read the file.
        	test.closeFile();//Calling the closeFile method in order to close the file.
        }//end main
    }//end class ReadTestHarness
    Java Code:
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.FileInputStream;
    import java.io.ObjectInputStream;
    import java.util.LinkedList;
    import java.util.Collections;
    import java.util.ListIterator;
    import java.util.List;
    
    public class ReadStudentGPA
    {
    	private ObjectInputStream input;
    	// no argument constructor
        public ReadStudentGPA()
        {
    
        }
        //end empty ReadStudentGPA constructor
    
        /**In this method openFile, we open the file and throw exceptions
         *for potential errors that may occur when opening the file
         */
    	public void openFile()
        {
        	/**In this try block we open file.We use an ObjectInputStream wrapped around a FileInputStream
        	 *in order to instantiate the file to be read.
        	 */
        	try
        	{
        		input = new ObjectInputStream(new FileInputStream("studentGPA.ser"));
        	}//end try
        	catch(IOException ioException)//
        	{
        		System.err.println("Error opening the file.");
        	}//end catch
        }
        //This method readGpaRecord will read the records from the file.
        public void readGpaRecord()
        {
    		GpaRecord record;//instantiating the GpaRecord object.
    
        	try//In this try block, the values are being input from the file.
        	{
    			while(true)
    			{
        			record = (GpaRecord) input.readObject();//This statement reads the records from the file.
    				LinkedList< GpaRecord > recordList = new LinkedList< GpaRecord >();
    				recordList.add(record);
    				System.out.println(recordList);
    				Collections.sort(recordList, new GpaComparator());
    				ListIterator iterator = recordList.listIterator();
    				while(iterator.hasNext())
    				{
        				System.out.println(iterator.next().toString());//Prints out the contents of the file in the toString method within the GpaRecord class.
    				}
        			/**Gets the Gpa of each student everytime the while loop executes and adds it to previous gpa then
        			 *stores it in the totalGpa variable
        			 */
    
    
    			}//end while
        	}//end try
        	catch(EOFException endOfFileException)
        	{
        		System.err.println("End of file was reached.");
        	}//end catch
        	catch(ClassNotFoundException classNotFoundException)
        	{
        		System.err.println("The class was not found");
        	}//end catch
        	catch(IOException ioException)
        	{
        		System.err.println("An error occured during the read from file.");
        	}//end catch
        }
    	/**
    	 *In this method, we are going to close the file.
    	 */
        public void closeFile()
        {
        	try//In this try block, we are testing if there are any more files to be read and if not, then we'll close the file.
        	{
        		if(input != null)
        			input.close();
        	} // end try
        	catch(IOException ioException)
        	{
        		System.err.println("Error closing file.");
        	} // end catch
        }//end method closeFile
    }//end class ReadStudentGPA
    Java Code:
    
    import java.io.Serializable;	// import Serializable tagging interface
    
    public class GpaRecord implements Serializable
    
      /*
       *	This class describes a student's summary GPA.
       *	No detail on a course-by-course basis is included
       *	This version of the Student GPA object implements interface Serializable
       *
       *	DO NOT MAKE CHANGES IN THIS CLASS
       *	Any changes made here will cause the studentGPA.ser file to be unusable.
      */
    
    {
       private String studentID;	// 8-digit identifier stored as a String
       private String lastName;
       private String firstName;
       private double gpa;			// GPA stored as a primitive double
       private int classCode;		// Classification - 1=Freshman, 2=Sophomore, etc.
    
       // five-argument constructor
       public GpaRecord( String id,
       					 String lName,
       					 String fName,
       					 int cCode,
       					 double grade )
       {
    		setStudentID( id );			// Constructor calls set methods for each instance
    		setLastName( lName );		//		variable rather than making direct assignments
    		setFirstName( fName );
    		setClassCode( cCode );
    		setGPA( grade );
    
       } // end five-argument Employee constructor
    
    
       // set student id number
       public void setStudentID( String id )
       {
          studentID = id; // should validate
       } // end method setStudentID
    
    
       // return social security number
       public String getStudentID()
       {
          return studentID;
       } // end method getSocialSecurityNumber
    
       // set last name
       public void setLastName( String lName )
       {
          lastName = lName; // should validate
       } // end method setLastName
    
    
       // return last name
       public String getLastName()
       {
          return lastName;
       } // end method getLastName
    
       // set first name
       public void setFirstName( String fName )
       {
          firstName = fName; // should validate
       } // end method setFirstName
    
       // return first name
       public String getFirstName()
       {
          return firstName;
       } // end method getFirstName
    
    
       //set class code 1=Freshman, 2=Sophomore, 3=Junior, 4=Senior
       public void setClassCode( int cCode )
       {
       	classCode = cCode;
       }	// end setClassCode
    
       //get class code
       public int getClassCode()
       {
       	return classCode;
       }	// end getClassCode
    
       //set GPA value
       public void setGPA( double grade )
       {
       	gpa = grade;
       }	// end method setGPA
    
       public double getGPA()
       {
       	return gpa;
       }	// end method setGPA
    
    
       /*
        * toString method overrides super-type definition.
        * This version is specific to the object class GpaRecord
        */
    
       public String toString()
       {
          return String.format( "\n%s %s \nStudent ID: %s\nClass Grouping: %d and GPA = %f",
          						getFirstName(),
          						getLastName(),
          						getStudentID(),
          						getClassCode(),
          						getGPA());
       } // end method toString
    
    }  	 // end class GpaRecord
    Java Code:
    import java.util.Comparator;
    
    /*
     *	Class implements interface Comparator
     *		and associates *this* custom comparator to
     *		object class GpaRecord
     *	By definition, all custom comparators must provide concrete
     *		implementation of method compare.  The method, by defintiion,
     *		must return an integer value that defines the relationship
     *		between two objects. A positive integer return indicates the first
     *		object instance has a greater value than the second.  A negative
     *		integer return indicates the second object instance has a greater value
     *		than the first.  A return of zero indicates equality in the object instances.
     */
    public class GpaComparator implements Comparator< GpaRecord >
    {
    	public int compare( GpaRecord gpaFirst, GpaRecord gpaSecond )
    	{
    		return ( gpaFirst.getClassCode() - gpaSecond.getClassCode() );
    
    	}	// end compare method
    }	// end class GpaComparator
    This is the output I am getting.
    Java Code:
    Tom Jordan 
    Student ID: 44521365
    Class Grouping: 3 and GPA = 2.630000
    
    Rick Nevin 
    Student ID: 12355487
    Class Grouping: 1 and GPA = 3.270000
    
    Charlie Piper 
    Student ID: 35715964
    Class Grouping: 4 and GPA = 3.140000
    
    Carole Bradshaw 
    Student ID: 22587964
    Class Grouping: 4 and GPA = 3.980000
    
    Sam Wells 
    Student ID: 44563218
    Class Grouping: 2 and GPA = 2.100000
    
    Marcus Williams 
    Student ID: 32547951
    Class Grouping: 3 and GPA = 3.650000
    
    Leonard Wolfe 
    Student ID: 11254987
    Class Grouping: 1 and GPA = 3.990000
    
    Nick Bradshaw 
    Student ID: 00548712
    Class Grouping: 4 and GPA = 2.510000
    
    Bill Cortell 
    Student ID: 88745236
    Class Grouping: 1 and GPA = 1.650000
    
    Ronn Kerner 
    Student ID: 23652147
    Class Grouping: 3 and GPA = 3.660000
    
    Pete Mitchell 
    Student ID: 33654871
    Class Grouping: 2 and GPA = 3.670000
    
    Charlotte Blackwood 
    Student ID: 66542187
    Class Grouping: 2 and GPA = 4.000000
    
    Rick Heatherly 
    Student ID: 99845213
    Class Grouping: 4 and GPA = 3.980000
    
    Tom Kazanski 
    Student ID: 12345678
    Class Grouping: 1 and GPA = 3.980000
    
    Mike Metcalf 
    Student ID: 88547126
    Class Grouping: 3 and GPA = 4.000000
    End of file was reached.

  2. #2
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    My problem is getting the LinkedList to print out correctly. I am not sure why it is not printing out as a list.

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

    Default

    Where's the question. Your code is too long. Create a SSCCE and ask a specific question.

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

    Default

    Can you inform me on what an SSCCE is? And my question to everybody is how do I get the LinkedList(located in the ReadStudentGpa class, method public void readGpaRecord()) to print out as a LINKED LIST, rather than how it is printing out right now?

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

    Default

    Quote Originally Posted by teekei View Post
    Can you inform me on what an SSCCE is?
    Google

    And my question to everybody is how do I get the LinkedList(located in the ReadStudentGpa class, method public void readGpaRecord()) to print out as a LINKED LIST, rather than how it is printing out right now?
    I asked for a specfic question. Your question is very broad. What does "print out as a LINKED LIST" mean? You provided an example of the output, so explain how that is not what you want and provide and example of what you do want instead. Overall you would change the code that is producing that output and make it print want you do want instead. If you want a more specific answer then ask a more specific question.

  6. #6
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    I apologize, I was under the assumption that those experienced in Java would be able to tell that the output of the program was not in LinkedList form. To be more specific, I would like my output to appear in LinkedList form(for those that know what that means), for example, having all the objects appear adjacently instead of vertically. Let me know if that was not specific enough or if I need to clarify further.

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

    Default

    No it is not specific enough. I still have no idea what you mean by LinkedList form. All my years of study and working in the industry this is the first time I have every heard it used.

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

    Default

    Despite your severe lack of information I think I know what your problem is. In your loop where you read the records from the file you create a new LinkedList everytime. You then add a single record to that list, sort it (not much point in sorting a list that contains only one object) and print it.

  9. #9
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    Oh ok, I was definitely mistaken and didn't know you weren't aware of what a linked list is. A linked list is a data structure used for collecting a sequence of objects, which allows efficient addition, removal and retrieval of elements from any position in the sequence.

    Here is an example of a linked list:

    [2, 5, 6, 8, 16, 20, 29, 40, 53, 53, 58, 61, 68, 70, 73, 73, 75, 77, 78, 85, 85, 87, 90, 91, 97]

    ^^^ This is a linked list of integers.
    I am trying to have my output in the same format, but instead of integers, have them printed out as whole objects, adjacent to each other when printed.

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

    Default

    I know what a LinkedList is. What I do not know is what you mean by LinkedList form. You seem to be under some assumption that LinkedLists should be displayed in some uniform style and that we should all know what that style is. Unless you specify EXACTLY how you want your data to be displayed how the frig are we supposed to know?

  11. #11
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    Quote Originally Posted by Junky View Post
    Despite your severe lack of information I think I know what your problem is. In your loop where you read the records from the file you create a new LinkedList everytime. You then add a single record to that list, sort it (not much point in sorting a list that contains only one object) and print it.
    Thats EXACTLY what I was looking for! Thank you! Now how would I go about doing this so I could have all the objects in one list?
    p.s. The sort is required for this assignment.

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

    Default

    Obviously you don't create a new LinkedList each time around the loop.

  13. #13
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    The program is showing an error, "illegal start of expression", how do I declare a LinkedList without getting this error? I'm stuck.

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

    Default

    SIGH!

    Why do I bother?
    sunde887 likes this.

  15. #15
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    Please refrain from answering my questions with a question. It would be greatly appreciated.

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

    Default

    I'll try to help you junky.

    @OP: When you have a problem, show us the problem, where does it occur? What is the exact error message? etc.

    Junky, and most people here are aware of what a linked list is, and a LinkedList isn't much different from a List when it comes to printing the elements in the Linked list.

    Java Code:
    public class LinkedList<T>{
      private class Node{
        T element;
        Node next;
      }
      private Node head;
      public String toString(){
        StringBuilder sb = new StringBuilder();
        while(head != null){
          sb.append(head.element);
          head = head.next;
        }
        return sb.toString();
      }
    }
    This is a quick idea of what a linked list looks like and probably is quite different than what you would see in the actual class, however, it's surprisingly similar to an ArrayList, or any List when implementing toString()

    Java Code:
    public class ArrayList<T>{ 
      private T[] items;
      private int count;
      public String toString(){
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < count; ++i){
          sb.append(items[i]);
        }
        return sb.toString();
      }
    }
    Notice how similar the toString methods are(they do basically the same thing, loop through the list appending each element).

    Another thing junky mentioned was that you are creating a Linked list each time through the loop, so each sort is only sorting a list of 1 item(which is useless), it was merely a hint that you are making a mistake.

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

    Default

    Quote Originally Posted by teekei View Post
    It would be greatly appreciated.
    It would be greatly appreciated if you provided details that allows us to help you.

  18. #18
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    I would like my objects that are in my output in this code...
    Java Code:
    Tom Jordan 
    Student ID: 44521365
    Class Grouping: 3 and GPA = 2.630000
    
    Rick Nevin 
    Student ID: 12355487
    Class Grouping: 1 and GPA = 3.270000
    
    Charlie Piper 
    Student ID: 35715964
    Class Grouping: 4 and GPA = 3.140000
    
    Carole Bradshaw 
    Student ID: 22587964
    Class Grouping: 4 and GPA = 3.980000
    
    Sam Wells 
    Student ID: 44563218
    Class Grouping: 2 and GPA = 2.100000
    
    Marcus Williams 
    Student ID: 32547951
    Class Grouping: 3 and GPA = 3.650000
    
    Leonard Wolfe 
    Student ID: 11254987
    Class Grouping: 1 and GPA = 3.990000
    
    Nick Bradshaw 
    Student ID: 00548712
    Class Grouping: 4 and GPA = 2.510000
    
    Bill Cortell 
    Student ID: 88745236
    Class Grouping: 1 and GPA = 1.650000
    
    Ronn Kerner 
    Student ID: 23652147
    Class Grouping: 3 and GPA = 3.660000
    
    Pete Mitchell 
    Student ID: 33654871
    Class Grouping: 2 and GPA = 3.670000
    
    Charlotte Blackwood 
    Student ID: 66542187
    Class Grouping: 2 and GPA = 4.000000
    
    Rick Heatherly 
    Student ID: 99845213
    Class Grouping: 4 and GPA = 3.980000
    
    Tom Kazanski 
    Student ID: 12345678
    Class Grouping: 1 and GPA = 3.980000
    
    Mike Metcalf 
    Student ID: 88547126
    Class Grouping: 3 and GPA = 4.000000
    End of file was reached.
    .... to mimic the format in this list
    [2, 5, 6, 8, 16, 20, 29, 40, 53, 53, 58, 61, 68, 70, 73, 73, 75, 77, 78, 85, 85, 87, 90, 91, 97]

    Still not sure if I properly detailed my problems...
    I also understand what Junky was saying about my loop, I am stuck in trying to figure out how I declare this LinkedList without declaring it as new through each iteration of the loop.

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

    Default

    You declare a new list before looping, so you are adding items to an existing linked list. Did you bother reading my previous post about how the toStrings work? The only reason numbers produce the list like that is because of the small amount of space they take up.

    Java Code:
    public String toString() {
            Iterator<E> i = iterator();
    	if (! i.hasNext())
    	    return "[]";
    
    	StringBuilder sb = new StringBuilder();
    	sb.append('[');
    	for (;;) {
    	    E e = i.next();
    	    sb.append(e == this ? "(this Collection)" : e);
    	    if (! i.hasNext())
    		return sb.append(']').toString();
    	    sb.append(", ");
    	}
        }
    Is the exact implementation details of toString for LinkedList(and other lists too). It doesn't have anything built into it that formats the elements in the list how you want it.

Similar Threads

  1. printing string backwards and printing every other
    By droidus in forum New To Java
    Replies: 22
    Last Post: 03-10-2011, 09:17 AM
  2. I can't get this to run correctly
    By LostinJavaLand in forum New To Java
    Replies: 4
    Last Post: 07-15-2010, 06:49 AM
  3. Having trouble with printing a blank line.
    By Meta in forum New To Java
    Replies: 4
    Last Post: 05-11-2010, 10:54 PM
  4. Having trouble looping & printing output
    By carrotcake in forum New To Java
    Replies: 1
    Last Post: 04-04-2010, 05:37 AM
  5. Having printing trouble
    By random0munky in forum New To Java
    Replies: 5
    Last Post: 12-07-2009, 09:27 PM

Posting Permissions

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