Improve company productivity with a Business Account.Sign Up

x
?
Solved

java help

Posted on 2009-05-06
4
Medium Priority
?
879 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 2000 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

595 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