Solved

java help

Posted on 2009-05-06
4
846 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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
The viewer will learn how to implement Singleton Design Pattern in Java.

708 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

16 Experts available now in Live!

Get 1:1 Help Now