SitePoint Sponsor

User Tag List

Results 1 to 13 of 13
  1. #1
    SitePoint Enthusiast
    Join Date
    Jan 2005
    Location
    Tennessee
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Unhappy reflist (linkedlist)

    Hey all i am trying to figure out how to get this RefList working for me...

    Implement a method countValue() that counts the number of times an item occurs in a linked list.

    int countValue(RefList f, int item);

    Generate 20 random numbers in the range of 0 to 4, and insert each number at the front of a linked list. Output the list by using a method which you would call writeLinkedList which you would add to the RefList.java program. In a loop, call the method countValue() , and display the number of occurrences of each value from 0 to 4 in the list.
    So far this is what i have:
    Code:
        public class PREX6
        {
               public static void main(String[] args)
               {
                  RefList refl1= new RefList();
                  int intRandomNum = 0;
                  int count = 0;
         
                  while (count != 21)
                  {
                        intRandomNum = (int)(Math.random() * 5);
                        refl1.add(intRandomNum);
                        count++;
                  }
         
                  System.out.println(refl1);
              }
        }
    But there's an error for the "refl1.add(intRandomNum);" since the RefList class does not have a "add" property. How am i supposed to add to a list that has no command to add?

    Here is the RefList code:
    Code:
        public class RefList
        {
          protected int numElements;          // number of elements in this list
          protected LLObjectNode currentPos;  // current position for iteration
         
          // set by find method
          protected boolean found;         // true if element found, else false
          protected LLObjectNode location; // node containing element, if found
          protected LLObjectNode previous; // node preceeding location
         
          protected LLObjectNode list;     // first node on the list
         
          public RefList()
          {
            numElements = 0;
            list = null;
            currentPos = null;
          }
        protected void find(Object target)
          // Searches list for an occurence of an element e such that
          // e.equals(target). If successful, sets instance variables
          // found to true, location to node containing e, and previous
          // to the node that links to location. If not successful, sets 
          // found to false.
          {
            boolean moreToSearch;
            location = list;
            found = false;
         
            moreToSearch = (location != null);
            while (moreToSearch && !found) 
            {
              if (location.getInfo().equals(target))  // if they match
               found = true;
              else
              {
                previous = location;
                location = location.getLink();
                moreToSearch = (location != null);
              }
            }
          }
        public int size()
          // Returns the number of elements on this list. 
          {
            return numElements;
          }
         
          public boolean contains (Object element)
          // Returns true if this list contains an element e such that 
          // e.equals(element); otherwise, returns false.
          {
            find(element);
            return found;
          }
        public boolean remove (Object element)
          // Removes an element e from this list such that e.equals(element)
          // and returns true; if no such element exists, returns false.
          {
            find(element);
            if (found)
            {
              if (list == location)     
                list = list.getLink();    // remove first node
              else
                previous.setLink(location.getLink());  // remove node at location
         
              numElements--;
            }
            return found;
          }
         
          public Object get(Object element)
          // Returns an element e from this list such that e.equals(element);
          // if no such element exists, returns null.
          {
            find(element);    
            if (found)
              return location.getInfo();
            else
              return null;
          }
        public String toString()
          // Returns a nicely formatted string that represents this list.
          {
            LLObjectNode currNode = list;
            String listString = "List:\n";
            while (currNode != null)
            {
              listString = listString + "  " + currNode.getInfo() + "\n";
              currNode = currNode.getLink();
            }
            return listString;
          }  
         
          public void reset()
          // Initializes current position for an iteration through this list,
          // to the first element on this list.
          {
            currentPos  = list;
          }
        public Object getNext()
          // Preconditions: The list is not empty
          //                The list has been reset
          //                The list has not been modified since most recent reset
          //
          // Returns the element at the current position on this list.
          // If the current position is the last element, then it advances the value 
          // of the current position to the first element; otherwise, it advances
          // the value of the current position to the next element.
          {
            Object next = currentPos.getInfo();
            if (currentPos.getLink() == null)
              currentPos = list;
            else
              currentPos = currentPos.getLink();
            return next;
          }
        }
    Mow this is what i have come up with for the "ADD":
    Code:
    public void add(Object element)
      // Adds element to this list.
      {
        //LLObjectNode currNode = list;
        //list = element;
    
        LLObjectNode current = head;
    
        // starting at the head node, crawl to the end of the list
        while(current.getNext() != null)
        {
           current.setNext(new LLNode(obj));
        }
        // the last node's "next" reference set to our new node
        current.setNext(new LLNode(obj));
        listCount++;// increment the number of elements variable
      }
    But of course it does not work.. Any help?

    Thanks!
    David

  2. #2
    SitePoint Wizard silver trophy rushiku's Avatar
    Join Date
    Dec 2003
    Location
    A van down by the river
    Posts
    2,056
    Mentioned
    0 Post(s)
    Tagged
    1 Thread(s)
    Where did RefList come from? Was it provided for you?

    If so, you should extend RefList to add the add method.

    If not...well, either way, why are you adding new variables when variables that are there to do what you're doing are already present? (eg: head and current, where are those coming from? They're not in the RefList class, did you add them some where you don't show?)

    Code:
        while(current.getNext() != null) {
           current.setNext(new LLNode(obj));
        }
    "While the current node's next value is not null, set the current node's next value to not null" Are you sure this is what you want?


    Style notes:
    - comments for methods come before the method definition
    - don't be lazy, always use braces to visually define your code sections (if, while, for, etc), you may need more than one line later and the time savings in time not spent figuring out why the line you just added always executes is well worth it.

  3. #3
    SitePoint Enthusiast
    Join Date
    Jan 2005
    Location
    Tennessee
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok i re-worked it and this is what i have now:
    Code:
    import java.util.Random;
    import java.lang.Integer;
    
    public class PREX6_2
    {
      public static void main(String[] args)
      {
        int temp;
        Integer item;
        Random random_numbers = new Random();
    
        //Generate a List of 20 random integers from 1-4
        RefUnsortedList myList = new RefUnsortedList();
    
        for (int i=0; i<20;i++)
        {
          temp = random_numbers.nextInt(5);
          item = new Integer(temp);
          myList.add(item);
        }
    
        //Now print the list
        myList.reset();
        
        //Now count and output values for 0-4
        for (int i=0;i<=4; i++)
        {
          temp = countValue(myList, i);
          System.out.println(i + ": " + temp);
        }
      }
    
      public static int countValue(RefUnsortedList f, int v)
      /**Count the number of instalnces of value v in a LinkedList of
      Integers f **/
      {
        int theReturn;
        int theList;
        int theValue = v;
    
        for (int a = 0; a < 20; a++)
        {
          theList = f.getNext();
    
          if (theList == theValue)
          {
            return (theValue);
          }
        }
        return (a);
      }
    }
    and here is the new code for the "add"
    Code:
    public class RefUnsortedList extends RefList implements UnsortedListInterface
    {
    
      public RefUnsortedList()
      {
        super();
      }
    
      public void add(Object element)
      // Adds element to this list.
      {
        LLObjectNode newNode = new LLObjectNode(element);
        newNode.setLink(list);
        list = newNode;
        numElements++;
      }
    }
    Code:
    public interface UnsortedListInterface extends ListInterface
    {
      void add(Object element);
      // Adds element to this list.
    }
    However i am unsure about what i need to do countValue() function.

    David

  4. #4
    SitePoint Wizard silver trophy rushiku's Avatar
    Join Date
    Dec 2003
    Location
    A van down by the river
    Posts
    2,056
    Mentioned
    0 Post(s)
    Tagged
    1 Thread(s)
    I would use an array of ints.

    Consider how the values 0 to 4 could correspond to an array of length 5.

    Again, method comments in the form

    /**
    this is what it does
    */
    method() {
    doing what the comments said
    }

    are far easier to read than

    method() {
    /**
    this is what it does
    */
    doing what the comments said
    }

    Think of it as the difference between

    I am about to tell you how to properly document your code.
    You should use comment blocks that appear before your method.

    and

    You should use
    I am about to tell you how to properly document your code.
    comment blocks that appear before your method.

  5. #5
    SitePoint Enthusiast
    Join Date
    Jan 2005
    Location
    Tennessee
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok...
    Code:
    import java.util.Random;
    import java.lang.Integer;
    
    public class PREX6_2
    {
      public static void main(String[] args)
      {
        int temp;
        Integer item;
        Random random_numbers = new Random();
        RefUnsortedList myList = new RefUnsortedList();
    
        //Generate a List of 20 random integers from 1-4
        for (int i=0; i<20;i++)
        {
          temp = random_numbers.nextInt(5);
          item = new Integer(temp);
          myList.add(item);
        }
    
        //Now print the list
        myList.reset();
        
        //Now count and output values for 0-4
        for (int i=0;i<=4; i++)
        {
          temp = countValue(myList, i);
          System.out.println(i + ": " + temp);
        }
      }
    
      // Count the number of instalnces of value v in a LinkedList of Integers f
      public static int countValue(RefUnsortedList f, int v)
      {
        int theList = 0;
        int theValue = v;
        int theCount = 0;
    
        // Count from 0 to 20
        for (int a = 0; a < 20; a++)
        {
          // Save current node in theList
          theList = f.getNext();
    
          // Compaire the node to the current passed static value
          if (theList == theValue)
          {
            // add to theCount if it equals
            theCount++;
          }
        }
        // Return theCounts' count back to function
        return (theCount);
      }
    }
    I am unable to figure out how to use the theList = f.getNext(); and save it as a int for compairing.. I gives me the error:
    Code:
    PREX6_2.java:43: incompatible types
    
    found   : java.lang.Object
    
    required: int
    
          theList = f.getNext();
    
                             ^
    Which i do not understand since its in the form of an int and its being saved as an int... What am i doing incorrect here?

    David

  6. #6
    SitePoint Wizard silver trophy rushiku's Avatar
    Join Date
    Dec 2003
    Location
    A van down by the river
    Posts
    2,056
    Mentioned
    0 Post(s)
    Tagged
    1 Thread(s)
    a: you're storing them as Integer Objects, you'll need to get the int value out of the Integers.
    b: getNext() returns an Object, you'll need to cast it to Integer.

  7. #7
    SitePoint Enthusiast
    Join Date
    Jan 2005
    Location
    Tennessee
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by rushiku View Post
    a: you're storing them as Integer Objects, you'll need to get the int value out of the Integers.
    b: getNext() returns an Object, you'll need to cast it to Integer.
    rushiku, like this?
    Code:
    theList = Integer.parseInt(f.getNext());
    Yeah, doesnt work either..

    David

  8. #8
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    no, you need to do:

    theList = (Integer) f.getNext();

    if you're using Java 5 or higher, if not you need to do

    theList = ((Integer) f.getNext()).intValue();

    The second one will work with all versions of Java

    Integer.parseInt will take a String like "25" and return the int 25.

  9. #9
    SitePoint Enthusiast
    Join Date
    Jan 2005
    Location
    Tennessee
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Awesome rozner! That seemed to work... But of course im still getting those last 3 errors that i do not know what to do with:
    Code:
    javac -Xlint:none  -d . -g -classpath . PREX6_2.java
    
    .\RefUnsortedList.java:11: RefUnsortedList is not abstract and does not override abstract method add(java.lang.Object) in ListInterface
    
    public class RefUnsortedList extends RefList implements UnsortedListInterface
    
           ^
    
    .\RefUnsortedList.java:19: add(java.lang.Object) in RefUnsortedList cannot implement add(java.lang.Object) in ListInterface; attempting to use incompatible return type
    
    found   : void
    
    required: boolean
    
      public void add(Object element)
    
                  ^
    
    .\UnsortedListInterface.java:11: add(java.lang.Object) in UnsortedListInterface clashes with add(java.lang.Object) in ListInterface; attempting to use incompatible return type
    
    found   : void
    
    required: boolean
    
      void add(Object element);
    
           ^
    
    3 errors
    And heres the code the errors refer too:
    Code:
    public class RefUnsortedList extends RefList implements UnsortedListInterface
    {
    
      public RefUnsortedList()
      {
        super();
      }
    
      public void add(Object element)
      // Adds element to this list.
      {
        LLObjectNode newNode = new LLObjectNode(element);
        newNode.setLink(list);
        list = newNode;
        numElements++;
      }
    }
    Code:
    public interface UnsortedListInterface extends ListInterface
    {
      void add(Object element);
      // Adds element to this list.
    }
    Code:
    public interface ListInterface
    {
      int size();
      // Returns the number of elements on this list.
    
      boolean contains (Object element);
      // Returns true if this list contains an element e such that 
      // e.equals(element); otherwise, returns false.
        
      boolean remove (Object element);
      // Removes an element e from this list such that e.equals(element)
      // and returns true; if no such element exists, returns false. 
      
      Object get(Object element);
      // Returns an element e from this list such that e.equals(element);
      // if no such element exists, returns null.
      
      String toString();
      // Returns a nicely formatted string that represents this list.
      
      void reset();
      // Initializes current position for an iteration through this list,
      // to the first element on this list.
    
      Object getNext();
      public boolean add(Object obj);
      // Preconditions: The list is not empty
      //                The list has been reset
      //                The list has not been modified since the most recent reset
      //
      // Returns the element at the current position on this list.
      // If the current position is the last element, then it advances the value 
      // of the current position to the first element; otherwise, it advances
      // the value of the current position to the next element.
    }
    David

  10. #10
    SiteP0int Weazle hooknc's Avatar
    Join Date
    Dec 2004
    Location
    Socialist Republic of Boulder
    Posts
    937
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by StealthRT View Post
    javac -Xlint:none -d . -g -classpath . PREX6_2.java

    .\RefUnsortedList.java:11: RefUnsortedList is not abstract and does not override abstract method add(java.lang.Object) in ListInterface

    public class RefUnsortedList extends RefList implements UnsortedListInterface

    ^

    .\RefUnsortedList.java:19: add(java.lang.Object) in RefUnsortedList cannot implement add(java.lang.Object) in ListInterface; attempting to use incompatible return type

    found : void

    required: boolean

    public void add(Object element)

    ^

    .\UnsortedListInterface.java:11: add(java.lang.Object) in UnsortedListInterface clashes with add(java.lang.Object) in ListInterface; attempting to use incompatible return type

    found : void

    required: boolean

    void add(Object element);

    ^

    David
    So yeah... what do the errors tell you? I know sometimes this error messages can be a little cryptic, but right now they are telling you exactly what you need to know.

    In your Parent class of RefList there must be an abstract method called add. This method most likely have a very specific method signature:

    public boolean add(Object element);

    The method signature (I think) is made up of all the access modifiers, the return type, the method name, and all the methods parameters.

    When you're overriding a method from a parent you must implement the Parents method signature.

    Notice your method returns void instead of a boolean. If you can return a boolean, my guess is those three errors will go away.

    Best of Luck.
    baby steps... baby steps...

  11. #11
    SitePoint Enthusiast
    Join Date
    Jan 2005
    Location
    Tennessee
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well from the code the "add" only adds whatever is placed into the list and does not need anything returned from that. So i figure the return would be void... But thats just with me guessing and looking at what the code "should" be doing.

    I set them all to void and it compiled... it seems to be working now..

    David

  12. #12
    SitePoint Wizard silver trophy rushiku's Avatar
    Join Date
    Dec 2003
    Location
    A van down by the river
    Posts
    2,056
    Mentioned
    0 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by hooknc View Post
    The method signature (I think) is made up of all the access modifiers, the return type, the method name, and all the methods parameters.
    Yes and no, specifically the return type. (the access modifier isn't really part of the signature at all, but if you change it, it may only be less restrictive than the parent class' modifier for that method)

    Yes, the return type is part of the signature (sort of...). No, changing it won't override a super class' method, nor will it overload a method in the same class - in fact, it won't compile in either case.

    Try this:
    Code:
    public class MethodOverride {
      public void method( Object object ) {}
    }
    
    class ExtendsMethodOverride extends MethodOverride {
      public boolean method( Object object ) {
        return true;
      }
    }
    and you get:

    method(java.lang.Object) in ExtendsMethodOverride cannot override method(java.lang.Object) in MethodOverride; attempting to use incompatible return type

    try this:
    Code:
    public class MethodOverride {
      public void method( Object object ) {}
      public boolean method( Object object ) {
        return true;
      }
    }
    and you get this:

    method(java.lang.Object) is already defined in MethodOverride

    Why? Because Java cannot determine which method you want to use based only on the type you are assigning the return value to (or not assigning to, in the cases of a void return value or an unassigned return value).

  13. #13
    SitePoint Wizard silver trophy rushiku's Avatar
    Join Date
    Dec 2003
    Location
    A van down by the river
    Posts
    2,056
    Mentioned
    0 Post(s)
    Tagged
    1 Thread(s)
    found : void
    required: boolean

    You get this when you try to do this:
    Code:
    void method(){}
    
    boolean bool = method();
    As the compiler said:
    "[ I ] found [that the method you invoked returns] void
    [but the type you are assigning the value to] required [a] boolean


Bookmarks

Posting Permissions

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