4 Replies - 1271 Views - Last Post: 10 October 2012 - 03:54 PM Rate Topic: -----

#1 scy0846  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 03-October 11

Creating an array with linked lists Forward display.

Posted 10 October 2012 - 09:11 AM

Ok my current project is to create an array of States objects and implement it as a linked list. I have a feeling I have done it wrong. I am to create the objects with a file named "States.2.Fall2012.txt".
I have that part down. I will start by giving you my main class.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package project3mitchell;

import java.io.IOException;

/**
 *
 * @author Taylor
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException
    {
       LinkedListController myLinkedListController;
       myLinkedListController = new LinkedListController(50);
       
       myLinkedListController.loadData("States.2.Fall2012.txt");
       myLinkedListController.sort();
       myLinkedListController.displayStates();
       
       
               
    }
}



My States Class <--here is where I believe I have the issue. My friend thinks my initial thought was correct here, but I think I am supposed to create the object here and then load the data in the Link class then make the Linked list in the Linked list controller. Does this sound right?

package project3mitchell;

/**
 *
 * @author Taylor
 */
public class States {

    public int regionNumber;
    private int statePopulation;
    private String stateName;
    private String stateCapital;
    private String stateAbbreviation;
    private String stateRegion;
    private Link first;               // ref to first item
    private Link last;                // ref to last item

    /**
     * Shows compiler what a States object is
     *
     * @param name: String
     * @param cap: String
     * @param abbr: String
     * @param pop: int
     * @param reg: String
     * @param regNum: int
     *
     * @returns States object
     */
    public States(String name, String cap, String abbr,
            int pop, String reg, int regNum) 
    {
        stateName = name;
        stateCapital = cap;
        stateAbbreviation = abbr;
        statePopulation = pop;
        stateRegion = reg;
        regionNumber = regNum;
        first = null;                  // no items on list yet     
        last = null;

    }// end State
//------------------------------------------------------------------------------

    /**
     * Obtains State Name.
     *
     * @param none
     *
     * @return stateName: String
     */
    public String getStateName() 
    {
        return stateName;
    }//end getStateName
//------------------------------------------------------------------------------

    /**
     * Obtains State Capital
     *
     * @param none
     *
     * @return stateCapital: String
     */
    public String getStateCapital() 
    {
        return stateCapital;
    }//end getStateCapital
//------------------------------------------------------------------------------

    /**
     * Obtains State Abbreviation
     *
     * @param none
     *
     * @return stateAbbreviation: String
     */
    public String getStateAbbreviation() 
    {
        return stateAbbreviation;
    }//end getStateAbbreviation
//------------------------------------------------------------------------------

    /**
     * Obtains State Region
     *
     * @param none
     *
     * @return stateRegion: String
     */
    public String getStateRegion() 
    {
        return stateRegion;
    }//end getStateRegion
//------------------------------------------------------------------------------

    /**
     * Obtains Region Number
     *
     * @param none
     *
     * @return regionNumber: int
     */
    public int getRegionNumber() 
    {
        return regionNumber;
    }//end getRegionNumber
//------------------------------------------------------------------------------   

    /**
     * Obtains State Population
     *
     * @param none
     *
     * @return statePopulation: int
     */
    public int getStatePopulation() 
    {
        return statePopulation;
    }//end getStatePopulation()
//------------------------------------------------------------------------------

    /**
     * Makes String of states.
     *
     * @param str: String
     * @param stateName: String
     * @param stateCapital: String
     * @param stateAbbreviation: String
     * @param stateRegion: String
     * @param regionNumber: int
     * @param statePopulation: int
     *
     * @return str: String
     */
    @Override
    public String toString() 
    {
        String str = String.format("%15s %15s %5s %12d %17s %5d",
                stateName, stateCapital, stateAbbreviation,
                statePopulation, stateRegion, regionNumber);
        return str;
    }// end toSTring()
//------------------------------------------------------------------------------
    public boolean isEmpty() // true if no links
    {
        return first == null;
    }
//------------------------------------------------------------------------------
    public void insertFirst(States dd) 
    {                          // if insert at front of list.  NO SEARCH!!
        Link newLink = new Link(dd);   // make new link		               
        if (isEmpty()) // if empty list,
        {
            last = newLink;                      // Points to end of list
        } else {
            first.previous = newLink;    
            newLink.next = first;           //    (Points to next link)
        }
        first = newLink;                  //(Points to start of Linked List)	
    }// end insertFirst()\
//------------------------------------------------------------------------------    
    public void insertLast(States dd) 
    {                         
        Link newLink = new Link(dd);   // make new link
        if (isEmpty()) // if empty list,
        {
            first = newLink;            // first --> newLink
        } else {
            last.next = newLink;        // old last 
            newLink.previous = last;    // old last 
        }
        last = newLink;                // newLink <-- last
    }
//-----------------------------------------------------------------------------
    public Link deleteFirst()         // delete first link
      {                              // (assumes non-empty list)
      Link temp = first;	// will return temp to calling environment.  
      if(first.next == null)         // if only one item
         last = null;                // null <-- last		
      else
         first.next.previous = null; // null <-- old next
      first = first.next;            // first --> old next
      return temp;
      }
//------------------------------------------------------------------------------    
    public Link deleteLast()          // delete last link
      {                              // (assumes non-empty list)
      Link temp = last;
      if(first.next == null)         // if only one item
         first = null;               // first --> null
      else
         last.previous.next = null;  // old previous --> null
      last = last.previous;          // old previous <-- last
      return temp;
      }
//------------------------------------------------------------------------------    
    public boolean insertAfter(States key, States dd)
      {                              // (assumes non-empty list)
      Link current = first;          // start at beginning
      while(current.dData != key)    
         {
         current = current.next;     // move to next link
         if(current == null)
            return false;            // didn't find it
         }  // end while()				
      Link newLink = new Link(dd);   
      if(current==last)              
         {
         newLink.next = null;        // newLink --> null
         last = newLink;             // newLink <-- last
         }
      else                           // not last link,
         {
         newLink.next = current.next; // newLink --> old next  
                                      // newLink <-- old next
         current.next.previous = newLink;		
         }
      newLink.previous = current;    // old current <-- newLink
      current.next = newLink;        // old current --> newLink
      return true;                   // found it, did insertion
      }
//------------------------------------------------------------------------------
    public Link deleteKey(States key)   // delete item w/ given key
      {                              // (assumes non-empty list)
      Link current = first;          // start at beginning
      while(current.dData != key)    
         {
         current = current.next;     // move to next link
         if(current == null)
            return null;             // didn't find it
         }
      if(current==first)             // found it; first item?
         first = current.next;       // first --> old next
      else                           // not first
                                     // old previous --> old next
         current.previous.next = current.next;       

      if(current==last)              // last item?
         last = current.previous;    // old previous <-- last
      else                           // not last
                                     // old previous <-- old next
         current.next.previous = current.previous;   
      return current;                // return value
      }
//------------------------------------------------------------------------------
   public void displayForward()
      {
      System.out.print("List (first-->last): ");
      Link current = first;          // start at beginning
      while(current != null)         // until end of list,
         {
         current.displayLink();      // display data
         current = current.next;     // move to next link
         }
      System.out.println("");
      }
//------------------------------------------------------------------------------
   public void displayBackward()
      {
      System.out.print("List (last-->first): ");
      Link current = last;           // start at end
      while(current != null)         // until start of list,
         {
         current.displayLink();      // display data
         current = current.previous; // move to previous link
         }
      System.out.println("");
      }
//------------------------------------------------------------------------------

}// end State() constructor



Link class

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package project3mitchell;

/**
 *
 * @author Taylor
 */
public class Link 
{
   public States    dData;            // data item
   // other instance data for this object as required.)
   public Link    next;         //next link in list (forward)
   public Link    previous;  //previous link in list (back)
   // -------------------------------------------------------------
   public Link(States d)                // constructor;  initializes attributes…
      { 
	dData = d; 
      } // end constructor
// -------------------------------------------------------------
   public void displayLink()          // display this link
      { 
	System.out.print(dData + " "); 
       } // probably uses a toString…
// -------------------------------------------------------------

}




Linked List Controller class

package project3mitchell;

import java.io.*;
/**
 *
 * @author Taylor
 */
public class LinkedListController 
{
    private States[] myStates;
    private int numStates = 0;
    public int swapCount;
    private boolean swap;

    /**
     * Creates a new state object
     *
     * @param maxSize 
     * @return new state object
     */
    public LinkedListController(int maxSize) 
    {
        myStates = new States[maxSize];
    } // end stateController()

    /**
     * Routine for loading data into the array of States 
     * from "States.2.Fall2012.txt".
     *
     * @param filename 
     * @throws IOException
     * @param name
     * @param cap
     * @param abbr
     * @param pop
     * @param reg
     * @param regnum
     * @return array of States objects from States.2.Fall2012.txt
     */
    public void loadData(String filename) throws IOException 
    {
        FileInputStream fis1 = new FileInputStream("States.2.Fall2012.txt"); 
        //obtains file statearray.txt
        BufferedReader br1 = new BufferedReader(new InputStreamReader(fis1)); 
        //reads statearray.txt
        int regnum, pop;
        String name, cap, abbr, reg;

        String inputString;
        inputString = br1.readLine();

        while (inputString != null) 
            //while loop to continually create state objects
        {
            name = inputString.substring(0, 15).trim(); 
            //parses the file for name
            cap = inputString.substring(15, 30).trim(); 
            //parses the file for capital
            abbr = inputString.substring(30, 32).trim(); 
            //parses the file for state abbreviation
            pop = Integer.parseInt(inputString.substring(32, 40).trim()); 
            //parses the file for population
            reg = inputString.substring(40, 55).trim(); 
            //parses the file for region
            regnum = Integer.parseInt(inputString.substring(55, 56).trim()); 
            //parses the file for region number

            myStates[numStates] = new States(name, cap, abbr, pop, reg, regnum); 
            //creates a new state object with attributes
            numStates++; //increases state count
            inputString = br1.readLine();
        } // end while (inputString != null) 
        br1.close();
    }//end loadData(String filename) throws IOException

    /**
     * Routine for displaying state objects.
     * 
     * @param index
     * @return myStates[index]
     */
    public void displayStates() 
    {
        int index; //index is a local variable for state objects

        for (index = 0;
                index < numStates;
                index++) 
         //for loop to continue making state objects stopping at numStates(50)
        {
            System.out.println(myStates[index]); 
            //displays state objects
        }//end for loop
    }//end displayStates()

    
    /**
     * Routine for sorting state objects.
     * 
     * @param in
     * @param out
     * @param min
     * @return sorted states.
     */
    public void sort() 
    {
        int in, out, min;
        swapCount = 0; //set number of swaps to zero
        for (out = 0;
                out < (numStates - 1);
                out++) //outer for loop
        {
            min = out;
            for (in = out + 1;
                    in < numStates;
                    in++) //inner for loop
            {
                if (myStates[in].getStateName().
                        compareTo(myStates[min].getStateName()) < 0) 
                    //compares state names for sorting
                {
                    min = in;
                    swap = true;                  
                }
            }//end inner for loop
            if (swap) 
            {
                swap(out, min);
                swap = false; 
            }
        }//end outer for loop 
    }//end sort()

    /**
     * Performs the swap for the sort function.
     * 
     * @param one: int
     * @param two: int
     * @return void
     */ 
    private void swap(int one, int two) 
    {
        States name = myStates[one];
        myStates[one] = myStates[two]; 
        myStates[two] = name;
        swapCount++; //increases swap count for every time swap is used
    }//end swap(int first, int next)
}



Is This A Good Question/Topic? 0
  • +

Replies To: Creating an array with linked lists Forward display.

#2 scy0846  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 03-October 11

Re: Creating an array with linked lists Forward display.

Posted 10 October 2012 - 09:33 AM

It may help to also state that I am trying to display it forward and backward using

   public void displayForward()
      {
      System.out.print("List (first-->last): ");
      Link current = first;          // start at beginning
      while(current != null)         // until end of list,
         {
         current.displayLink();      // display data
         current = current.next;     // move to next link
         }
      System.out.println("");
      }
//------------------------------------------------------------------------------
   public void displayBackward()
      {
      System.out.print("List (last-->first): ");
      Link current = last;           // start at end
      while(current != null)         // until start of list,
         {
         current.displayLink();      // display data
         current = current.previous; // move to previous link
         }
      System.out.println("");
      }


I have this part in the States class

Then I am trying to implement it here in the LinkedListController class

/**
     * Routine for displaying state objects.
     * 
     * @param index
     * @return myStates[index]
     */
    public void displayForwardStates() 
    {
        int index; //index is a local variable for state objects

        for (index = 0;
                index < numStates;
                index++) 
         //for loop to continue making state objects stopping at numStates(50)
        {
            System.out.println(myStates[index].displayForward()); 
            //displays state objects
        }//end for loop
    }//end displayStates()


it claims I cannot use a void type here
Was This Post Helpful? 0
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: Creating an array with linked lists Forward display.

Posted 10 October 2012 - 11:35 AM

displayForward() is a void method which means it returns nothing
you can println() a method that returns nothing as in:

System.out.println(myStates[index].displayForward());
Was This Post Helpful? 0
  • +
  • -

#4 scy0846  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 03-October 11

Re: Creating an array with linked lists Forward display.

Posted 10 October 2012 - 03:44 PM

I figured that part out. sorry. Now I am stuck on the displayForwardStates with a new problem.

I’m not sure why this isn’t working. Java isn’t giving me an error
I have this in my StateController class


public void insertLinks()
    {
        for(int index=0; //index is a local variable for state objects
                index < numStates;
                index++) 
         //for loop to continue making state objects stopping at numStates(50)
        {
            myList.insertFirst(myStates[index]);
        }
    }


This should work right?

My insertFirst code in my LinkList class is


public void insertFirst(States dd) 
    {                          // if insert at front of list.  NO SEARCH!!
        Link newLink = new Link(dd);   // make new link                                       
        if (isEmpty()) // if empty list,
        {
            last = newLink;                      // Points to end of list
        } else {
            first.previous = newLink;    
            newLink.next = first;           //    Points to next link
        }
        first = newLink;                  //Points to start of Linked List           
    }// end insertFirst()

Was This Post Helpful? 0
  • +
  • -

#5 scy0846  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 03-October 11

Re: Creating an array with linked lists Forward display.

Posted 10 October 2012 - 03:54 PM

Exception in thread "main" java.lang.NullPointerException
at project3mitchell.StateController.insertLinks(StateController.java:168)
at project3mitchell.Main.main(Main.java:25)


Those are the errors I am getting
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1