Solved

java help

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Apps blocked by Java 9 88
MySQL  on Tomcat 8 68
Opening PDF on button click and fill new document 2 47
Selenium docs api java index 3 48
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues undeā€¦
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importingā€¦
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

808 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