Solved

java help

Posted on 2009-05-06
4
847 Views
Last Modified: 2012-05-06
(finding the largest object) Write a metod that returns the largest object in an array of objects. The method signature is:
public static Object max(Comparable[] a)

All the objects are instances of the Comparable interface. The order of the objects in the array is determined using the compareTo method.

write a test program that creates an array of ten strings, an array of ten integers, and an array of ten dates, and finds the largest string, integer, and date in the arrays.

I'm having problems in my main how to put the dates in an array this is the only part of the code im having issues with. could someone please help me get started on how i go about doing this. thanks
import java.util.Date;
 
 

public class maxobject 

{
 

    public static int findMax(int[] nums) 

    {

        int curMax = nums[0];

        for (int i=1; i<nums.length; i++) 

        {

            if (nums[i] > curMax) 

            {

                curMax = nums[i];

            }

         }
 

        return curMax;

    }
 

   

    public static String findMax(String[] strs) 

    {

      

        String curMax = strs[0];

        for (int i=1; i<strs.length; i++) 

        {

            if (strs[i].length() > curMax.length()) 

            {

                curMax = strs[i];

            }

        }
 

        return curMax;

    }

    

    public static Date findMax(Date[] date)

    {

    	Date curMax = new Date();

    	curMax = date[0];

    	for(int i=1;i<date.length;i++)

    	{

    		if(date[i].compareTo(curMax)>0)

    		{

    			curMax=date[i];

    			

    		}

    		else if(date[i].compareTo(curMax)>0)

    		{

    			curMax = date[i];

    		}

    	}

    	return curMax;

    }
 

    public static void main(String args[])

    {

    	int[] nums = {1,2,3,4,5,6,7,8,9,10};

    	System.out.println("The max interger is: " +maxobject.findMax(nums));

    	String[] strs = {"apple","pear","orange","ten","a","is","building","program","baseball","cowboy"};

    	System.out.println("The max string is: " +maxobject.findMax(strs));

    }

}

Open in new window

0
Comment
Question by:laughsalot
  • 2
4 Comments
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 24320671
Date dates = new Date[10];
for (int i=0; i
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24321040
Try something like:
        Date[] dates = new Date[10];

        for (int i=0; i<dates.length; i++) {

            // Create a random date approximately sometime in the last 40 years

            long time = (long)(Math.random() * 20L * 1000 * 60 * 60 * 24 * 365);

            dates[i] = new Date(time);

            System.out.println(dates[i]);

        }   

Open in new window

0
 
LVL 3

Expert Comment

by:avdej
ID: 24326768
Hi laughsalot!

After I've considered your code I'm afraid you misunderstood the task description provided by your prof.
You MUST NOT write several specialized methods for getting max value. Instead, you have to write a SINGLE (i.e. universal) method to do that by means of Comparable interface.

To explain you the point I have written a full working version of a class which provides the solution to the task description above. (Although it is not a homework site I found that the best and shorter way to explain you the point).

Examine the class in the attached code snippet thoroughly. Compile, run, modify and play with it. You will find there anything you need to understand the issue.

Let me know if I can be of further assistance.

Avdej
import java.util.*;
 
 

public class GetMaxComparable

{
 

    static public void main(String[] args)

    {

        int len = 10;

        Integer[] arrOfInt = getArrOfInt(len, 1000);

        String[] arrOfString = getArrOfString(len, 8);

        Date[] arrOfDate = getArrOfDate(len, System.currentTimeMillis());

        

        System.out.println("Array of random Integers:");

        printArray(arrOfInt);

        System.out.println("Max Integer: " + max(arrOfInt));

        System.out.println();

        

        System.out.println("Array of random Strings:");

        printArray(arrOfString);

        System.out.println("Max String: " + max(arrOfString));

        System.out.println();

        

        System.out.println("Array of random Dates:");

        printArray(arrOfDate);

        System.out.println("Max Date: " + max(arrOfDate));

        System.out.println();

    }

    

    

    /**

     Determines max value in an array of Comparable objects

    */

    static public Object max(Comparable[] arr)

    {

        if (arr == null || arr.length == 0) return null;

        

        Comparable maxVal = arr[0];

        

        for (int i = 1; i < arr.length; ++i)

        {

            maxVal = maxVal.compareTo(arr[i]) < 0 ? arr[i] : maxVal;

        }

        

        return maxVal;

    }
 
 

    /**

     Creates an array of 'len' random Integers in range from 1 to 'maxVal'

    */

    static private Integer[] getArrOfInt(int len, int maxVal)

    {

        Integer[] arr = new Integer[len];

        

        for (int i = 0; i < len; ++i)

        {

            arr[i] = new Integer((int)(Math.random() * 1000) + 1);

        }

        

        return arr;

    }

    

    

    /**

     Creates an array of 'len' random Strings with length 'strLen'

     each built from uppercase english letters

    */

    static private String[] getArrOfString(int len, int strLen)

    {

        String[] arr = new String[len];

        

        char minChar = 'A';

        char maxChar = 'Z';

        int charRange = maxChar - minChar + 1;

        

        for (int s = 0; s < len; ++s)

        {

            char[] chars = new char[strLen];

            for (int i = 0; i < strLen; ++i)

                chars[i] = (char)(minChar + Math.random() * charRange);

            

            arr[s] = new String(chars);

        }

        

        return arr;

    }

    

    

    /**

     Creates an array of 'len' random Dates in range from 'January 1, 1970'

     till the Date corresponding to 'millis' parameter

    */

    static private Date[] getArrOfDate(int len, long millis)

    {

        Date[] arr = new Date[len];

        

        for (int d = 0; d < len; ++d)

        {

            arr[d] = new Date((long)(Math.random() * millis) + 1L);

        }

        

        return arr;

    }

    

    

    /**

     Prints an array of Objects one object per line

    */

    static public void printArray(Object[] arr)

    {

        int len;

        

        if (arr == null) { System.out.println("null"); return; }

        else if ((len = arr.length) == 0) { System.out.println("[]"); return; }

        

        for(int i = 0; i < len; ++i)

        {

            System.out.println(arr[i]);

        }

    }
 

}

Open in new window

GetMaxComparable.java.txt
0
 
LVL 3

Expert Comment

by:avdej
ID: 24327075
UPDATE NOTE:
I've just noticed a spot in my code that has to be updated/corrected for completeness.
Please do at line 58 (in order to be able to change the range of generated random Integers):
replace literal value '1000' with variable name 'maxVal'.

Avdej
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Printing to a specific printer tray (HP 806dn printer) 3 83
create a gui in perl 3 70
github account with ecipse 1 42
Windows 10 IE Certificate Issue 10 41
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now