Page 2 of 2 FirstFirst 12
Results 21 to 40 of 40
  1. #21
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Ok, so I would build the findMax with no parameters like I had it above, then instead of < or > simply replace them with compareTo.XXXX?

    Think I'm having a problem calling the method here, well I'm obviously having a problem grasping it ;/.

  2. #22
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You would use compareTo to compare one DataElement with another, specifically, in your for loop, as you iterate through your list of DataElements, you'd call compareTo on your max element and pass into the method the the i'th element (again, as you're iterating through the array). Then based on the int returned, you'd either leave max element untouched or you'd set it to be the i'th element of the array.

    Not to confuse you, but you could even call it the other way around... call compareTo on the i'th element and pass the max element into the methods parameter, but then you'd have to change your if block where you check the int returned by this method. This means that the method has an inverse symmetry of sorts. Calling:

    dataElementA.compareTo(dataElementB) == -dataElementB.compareTo(dataElementA);

    is true
    Last edited by Fubarable; 09-12-2009 at 07:24 PM.

  3. #23
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Ok, getting a bit farther but this is where I'm getting stuck again

    Java Code:
    public DataElement findMax()
    {
    	for (int i=0; i < list.length; i++) 
    	{
    	      if (list[i].compareTo(maxElement)) 
    	      {
    	         maxElement = list[i];
    	      }
    	}
      	return maxElement;
    }
    These are the errors I'm getting, same as before.

    Java Code:
    ArrayListClass.java:259: compareTo(DataElement) in DataElement cannot be applied to (int)
    	      if (list[i].compareTo(maxElement)) 
    	                 ^
    ArrayListClass.java:261: incompatible types
    found   : DataElement
    required: int
    	         maxElement = list[i];
    	                          ^
    ArrayListClass.java:264: incompatible types
    found   : int
    required: DataElement
      		return maxElement;
      		       ^
    3 errors

  4. #24
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Please look at your own code and look at your comments in the code for DataElement with regard to the compareTo method. What is confusing about that?

    In other words the if logic check requires a boolean expression. However the compareTo method doesn't return a boolean but returns an int, right? But you can still use that int to make a boolean expression (again see the comments in your own DataElement class). You should be able to figure this out. I have faith.
    Last edited by Fubarable; 09-13-2009 at 12:01 AM.

  5. #25
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Will do, I think I've been staring at it so long that i'm getting a case of programming blindness, even the easiest things seem to slip by, so I'll walk away, come back and see what I can get banged out. Thanks for the help, I'll get it one way or another :).

  6. #26
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Dunno, been playing with this again all morning, I just don't get it. I understand the compareTo method from my dataelement, but once I go to place it in that block of code to find the max it just not fitting. Think here again I'm just getting to frustrated with something that should be simple, making it alot worse than it should be.

    I wrote up a quick program to check the values and return the max and it work, but if i take that method and move it into my class, then try to call it from my other test program it doesn't work at all. Are there any compareTo methods like this for examples floating around, I haven't been able to find a single one.
    Last edited by SMHouston; 09-13-2009 at 08:42 PM.

  7. #27
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Let's look again at a simple findMax method, one that finds a max in an int array. It makes the max element the first element of the array, then steps through the array using a for loop, and if any element is found to be greater than the max element, it makes that current element the max element:
    Java Code:
    // assume that the class has an int[] called array
    public int findMax() {
      int maxElement = array[0];
      for (int i=0; i<array.length; i++) {
    
         // if the current array element is greater than the max element
         if (array[i]>maxElement) {
            maxElement = array[i]; // make current the max element
         }
      }
      return maxElement;
    }
    Understand it?

    Now let's read the comments associated with the compareTo method again:
    Java Code:
        public abstract int compareTo(DataElement otherElement);
          //Method to compare two objects.
          //Postcondition: Returns a value < 0 if this object is 
          //                    less than the object otherElement;
          //               Returns 0 if this object is the same as 
          //                    the object otherElement.
          //               Returns a value > 0 if this object is 
          //                  greater than the object otherElement.
    So, what if our class has an array of DataElement, say
    Java Code:
    DataElement[] list
    Is there any way to create a findMax method that is similar and uses DataElement's compareTo method? Let's walk through this one step at a time.

    First of all, the method will return the greatest element in the array, so it will return a DataElement object. Our method signature must reflect this:
    Java Code:
    // assume that the class has an DataElement[] called list
    public DataElement findMax() {
    Now the method will declare a maxElement DataElement variable and set it equal to the first element in the list array:
    Java Code:
      DataElement maxElement = list[0];
    Now we will iterate through the list array one item at a time:
    Java Code:
      for (int i = 0; i < list.length; i++) {
    So far, except for using DataElement instead of int, this code is not much different from the code above.

    But now comes the trickier part: finding out if the current element is larger than that held by the maxElement variable. We can't do this:
    Java Code:
         if (list[i] > maxElement) {
    since the greater than operator has no meaning with DataElement objects. Here is where we use compareTo. We know that if we call compareTo on the current element and pass the maxElement into the method, if it returns a number > 0, then the current element is "greater" than the max element. And so we use this knowledge:
    Java Code:
         if (list[i].compareTo(maxElement) > 0) {
            maxElement = list[i]; // make current the max element
         }
    And except for returning maxElement at the end of the method, that's really all there is to it.
    Last edited by Fubarable; 09-13-2009 at 08:47 PM.

  8. #28
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by SMHouston View Post
    Are there any compareTo methods like this for examples floating around, I haven't been able to find a single one.
    Do a search in Google, this and in other forums on the term "Comparable". This is an interface that has one method: compareTo. You should find a ton of examples by doing this.

    For example:
    the compareTo method

    Java Tips - How to use Comparable Interface

    interface purpose?

    Sort it out - JavaWorld

  9. #29
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    OK, that makes much more sense and thank you very much, dunno why I just wasn't grasping that.

    Finding the Min I would just do :

    Java Code:
    public DataElement findMin()
    {
       DataElement minElement = list[0];
       for (int i = 0; i < list.length; i ++)
       {
            if (list[i].compareTo(minElement) < 0)
            {
                    minElement = list[i];
            }
        }
        return minElement;
    }
    Once I try calling the method in my main program like this :

    Java Code:
    intList.findMax();	
    System.out.println();
    System.out.print("The max element in the list is : " + intList.findMax());
    I get this error :

    Java Code:
    Exception in thread "main" java.lang.NullPointerException
    at ArrayListClass.findMax(ArrayListClass.java:260)
    at Example3_1.main(Example3_1.java:48)
    Does that mean the program is pointing to something that isn't there?

  10. #30
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    when you get a null pointer exception (NPE) it means that you're trying to "dereference" an object that has not been initialized yet. My guess is that here the culprit is intList.

  11. #31
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    intList is initialized and it returns and prints out the list the user has entered.

    Java Code:
    public static void main(String[] args) throws IOException
        {
            UnorderedArrayList intList
                              = new UnorderedArrayList(50);             //Line 1
            UnorderedArrayList temp =
                                new UnorderedArrayList();               //Line 2
    
            IntElement num = new IntElement();                          //Line 3
    		  
            int counter;                                                //Line 4
            int position;                                               //Line 5
    		  
            StringTokenizer tokenizer;                                  //Line 6
    
            System.out.println("Line 7: Processing the "
                             + "integer list");                         //Line 7
            System.out.print("Line 8: Enter 8 integers on the "
                            + "same line: ");                           //Line 8
            System.out.flush();                                         //Line 9
    
            tokenizer = new
                       StringTokenizer(keyboard.readLine());            //Line 10
    
            for(counter = 0; counter < 8; counter++)                    //Line 11
            {
                num.setNum(Integer.parseInt(tokenizer.nextToken()));    //Line 12
                intList.insert(num);                                    //Line 13
            }
    
            temp.copyList(intList);                                     //Line 14
    
            System.out.println();                                       //Line 15
            System.out.print("Line 16: The list you "
                           + "entered is: ");                           //Line 16
            intList.print();                                            //Line 17
            System.out.println();                                       //Line 18
    			
    		  intList.findMax();	
    		  System.out.println();
    		  System.out.print("The max element in the list is : " + intList.findMax());
    I've tried to use the temp list but that bring back the error :

    findMax() in ArrayListClass cannot be applied to (UnorderedArrayList)

  12. #32
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    7

    Default

    Your findMax method is to blame. If you read the exception trace carefully you will see that it tells you the exact line number where a null was dereferenced.

  13. #33
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Ok, so my two methods :

    Java Code:
    public DataElement findMax()
    {
    	DataElement maxElement = list[0];
    	for (int i = 0; i < list.length; i++)
    	{
    		if (list[i].compareTo(maxElement) > 0)
    		{
    			maxElement = list[i];
    		}
    	}
    	return maxElement;
    		
    }
    		
    public DataElement findMin()
    {
    	DataElement minElement = list[0];
    	for (int i = 0; i < list.length; i++)
    	{
    		if (list[i].compareTo(minElement) < 0)
    		{
    			minElement = list[i];
    		}
    	}
    	return minElement;
    }
    These are returning a "Null" value? I don't need a set/get method though do i?

    Specifically these two lines are being referenced

    Java Code:
    if (list[i].compareTo(minElement) < 0)
    
    if (list[i].compareTo(maxElement) > 0)
    I've tried to declare and initialize the minElement and maxElement in my default constructor but that did nothing. Besides they are declared below, even then shouldn't they be returning the first element in the list if anything?
    Last edited by SMHouston; 09-13-2009 at 09:53 PM.

  14. #34
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    7

    Default

    You should be using System.out.prinln to verify values of the variables.
    Print the values of list[i] before calling compareTo on them.

  15. #35
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Ok, figured it out with the system.out.println so I'm editting this.

    Ok this is what I get from the print out.

    1
    2
    3
    4
    5
    6
    7
    8
    null

    1-8 is what I entered, now is this because I have the intList set to (50);?
    Last edited by SMHouston; 09-13-2009 at 10:24 PM.

  16. #36
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    7

    Default

    You would put the printlns before the line reported for the exception.
    Then you should read the console to see what is printed out before the N.P.E error.

  17. #37
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Hmmm, this doesn't throw an NPE for you?
    Java Code:
    public class Fu3 {
      public static void main(String[] args) {
        throwNPE(null);
      }
      
      public static void throwNPE(String f) {
        System.out.println("this will cause a null pointer exception " + f.length());
      }
    }

  18. #38
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Ok, yup I got it. It was because intList was initialized to 50, once I set it to 8 it works fine. Thanks for the help once again, very much appreciated, learned alot this go around and hopefully I won't have any more compareTo questions for ya :).

    Now is there a way to put an error check in there so I can initialize it to say 100 and if the user only enters 7 numbers it will not throw a null error?

  19. #39
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    7

    Default

    Don't use arrays if you don't know what the length is going to be. Use ArrayList instead.

  20. #40
    SMHouston is offline Member
    Join Date
    Sep 2009
    Posts
    80
    Rep Power
    0

    Default

    Ok will do, thanks again. Now onto trying to figure out the gregorian calendar.

Page 2 of 2 FirstFirst 12

Similar Threads

  1. How to access element in a CSV?
    By venkatteshb in forum New To Java
    Replies: 11
    Last Post: 08-17-2008, 11:37 AM
  2. how can we get the element of by using the hashtable
    By raj reddy in forum Web Frameworks
    Replies: 1
    Last Post: 05-06-2008, 01:45 PM
  3. ArrayList problem (finding largest no)
    By bugger in forum New To Java
    Replies: 3
    Last Post: 12-12-2007, 12:47 PM
  4. Max element in an Array
    By mew in forum New To Java
    Replies: 5
    Last Post: 12-03-2007, 05:26 PM
  5. a no such element exception
    By headlice1 in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 05:36 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
  •