Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts

    trouble returning an index to the main method

    I have effectively figured out how to draw information from the arrays in my code. Originally, I was to print the name and time of a winner in a marathon. This was pretty simple. However, I have a conceptual problem with the next instruction. I need to write a second method to find the 2nd fastest runner. This new method needs to use the first method to find the fastest time, then loop through all the values to find the 2nd lowest time.

    I figured that the new method could remove an element from the times[] array, loop through the data (which is now missing the fastest time), and pass the new resulting array back to the main.

    I'm kind of lost on how to return the new array and cycle it through the main method appropriately.
    [/CODE]

    public class Marathon {

    public static int removeElement(int[] times, int removeIndex){
    int second = times[0];
    for (int i = removeIndex; i < times.length - 1 ; i++){
    times[i] = times[i+1];
    second = times[i];
    }
    return second;
    }

    public static void main (String[] arguments) {
    String[] names = {

    "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex",

    "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda",

    "Aaron", "Kate"

    };
    int[] times = {

    341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299,

    343, 317, 265

    };

    int removeIndex = 0;

    for (int i = 0; i < names.length; i++) {
    System.out.println(names[i] + ": " + times[i]);
    }
    int min = times[0];

    String winner = null;
    for (int i = 1; i < times.length; i++){
    if (times[i] < min){
    min = times[i];
    winner = names[i];
    }
    int secondFastest = removeElement(times, removeIndex);
    }

    System.out.println("The fastest runner finished the race in " + min + " total minutes.");


    System.out.println("The winner is " + winner + ".");


    }

    }
    [/CODE]
    Last edited by Skuby35; 02-17-2011 at 02:09 PM.

  • #2
    New Coder
    Join Date
    Feb 2011
    Posts
    48
    Thanks
    1
    Thanked 2 Times in 2 Posts
    This is NOT a good approach, because you'll lose data when you run your method. The best approach is to store the best index and to not include the given index into your search. This way you won't lose data

  • #3
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts

    trouble returning an index to the main method

    okay, I restructured my code so i have a method named getMinIndex that returns minIndex. I have another method that returns secondIdx. The idea is to call these methods and print the values associated with the returned indexes. I did a huge rewrite here. Help from all would be greatly appreciated.

    Right now all it prints is the array itself. I need it to take the returned index, associate it to the array and print off the name and time tied to that index.
    I will have 2 print statements, one for the winner of the race and one for second place.

    [/CODE]
    public class Marathon2 {

    public static void main(String[] args) {
    String[] names = {
    "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex",
    "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda",
    "Aaron", "Kate"
    };
    int[] times = {
    341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299,
    343, 317, 265
    };
    for (int i = 0; i < names.length; i++) {
    System.out.println(names[i] + ": " + times[i]);
    }

    }
    public static int getMinIndex(int[] times){
    int minTime = Integer.MAX_VALUE;
    int minIndex = 0;

    for (int i = 0; i<times.length; i++){
    if (times[i] < minTime){
    minTime = times[i];
    minIndex = i;
    }
    }
    return minIndex;
    }
    public static int getSecondMinIdx(int[] times){
    int secondIdx = 0;
    int minIdx = getMinIndex(times);

    for ( int i = 0; i<times.length; i++){
    if (secondIdx == 0 ||
    times[i] < times[secondIdx])
    secondIdx = i;
    }
    return secondIdx;
    }
    }
    [/CODE]

  • #4
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    If you are just looking to print out the second array values, simply write a method that prints both easily:
    PHP Code:
    public static String getRunnerTime(int i)
    {
        
    String sResult;
        try
        {
            
    sResult names[i] + ": " times[i];
        }
        catch (
    Exception ex// Can toss an IndexOutOfBounds exception, and technically a NullPointer, but I'll just sweep all potentials.
        
    {
            
    sResult ex.getMessage();
        }
        return 
    sResult;

    And look up that way.

    Why are you approaching this by using two arrays? You're better off using an Object[] (cast to the class would be better) or a collection, and corresponding the name directly with the time, and using a compareTo or comparator in order to fetch the order (useful when sorting and stuff too). Alternatively, a hashmap of name => time would work as well, but one or the other has to be unique in order to not have it overwrite (I'd assume name is more unique than time). The runner object makes a lot more sense:
    PHP Code:
    public class MarathonRunner
    {
        private 
    String sName;
        private 
    int iTime;

        
    // Replicate comparators for each desired sort, or provide comparators in different scope (you need to write mutators and accessors for those).
        
    public static Comparator<MarathonRunnercompareByTimeASC = new Comparator<MarathonRunner>()
        {
            public 
    int compare(MarathonRunner mr1MarathonRunner mr2)
            {
                return 
    mr1.iTime mr2.iTime;
            }
        };

        public 
    MarathonRunner(String sNameint iTime)
        {
            
    this.sName sName;
            
    this.iTime iTime;
        }

        
    // Add accessors and mutators if desired (accessors are really quite necessary)
        
    public String getName()
        {
            return 
    this.sName;
        }
        
        public 
    int getTime()
        {
            return 
    this.iTime;
        }
        
        
        public static 
    void main(String[] argv)
        {
            
    ArrayList<MarathonRunneralm = new ArrayList<MarathonRunner>();
            
    alm.add(new MarathonRunner("Elena"341));
            
    alm.add(new MarathonRunner("Thomas"273));
            
    alm.add(new MarathonRunner("Hamilton"278));
            
    // ...
            // Sort works on a reference, if you want to keep the arbitrary order
            // of alm, you'll need to clone it.  ArrayList provides a shallow clone
            
    Collections.sort(almMarathonRunner.compareByTimeASC);

            
    // Lowest time:
            
    MarathonRunner lowest alm.get(0);
            
    System.out.println(lowest.getName() + ": " lowest.getTime());

            
    // Highest time:
            
    MarathonRunner highest alm.get(alm.size() - 1);
            
    System.out.println(highest.getName() + ": " highest.getTime());
        }

    For example (untested, but works ok in my head lol). This allows far greater control than the reliance on two arrays. Another great idea would be to have a MarathonRunners class that extends ArrayList<MarathonRunner> (or any other type of collection for that matter). This lets you control things and add new methods for sorting and whatnots collected in a single location which is much handier than adding a comparator variable in a base class.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #5
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Figured it out the easy way.

    [/CODE]
    public class Marathon2 {

    /**
    * @param args
    */
    public static void main(String[] args) {
    String[] names = {
    "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex",
    "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda",
    "Aaron", "Kate"
    };
    int[] times = {
    341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299,
    343, 317, 265
    };
    for (int i = 0; i < names.length; i++) {
    System.out.println(names[i] + ": " + times[i]);
    }
    int h = getMinIndex(times);
    int i = getSecondMinIdx(times);

    System.out.println("The winner of the race was " + names[h] + ", with a blistering time of " + times[h] + " minutes.");
    System.out.println("The runner-up, " + names[i] + ", recieved a speedy time of " + times[i] + " minutes.");

    }
    public static int getMinIndex(int[] times){
    int minTime = Integer.MAX_VALUE;
    int minIndex = -1;

    for (int i = 0; i<times.length; i++){
    if (times[i] < minTime){
    minTime = times[i];
    minIndex = i;
    }
    }
    return minIndex;
    }
    public static int getSecondMinIdx(int[] times){
    int secondIdx = -1;
    int minIdx = getMinIndex(times);

    for ( int i = 0; i<times.length; i++){
    if (i == minIdx)
    continue;
    if (secondIdx == -1 ||
    times[i] < times[secondIdx])
    secondIdx = i;
    }
    return secondIdx;
    }
    }
    [/CODE]
    Last edited by Skuby35; 02-19-2011 at 08:02 AM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •