Results 1 to 7 of 7
  1. #1
    jpab29 is offline Member
    Join Date
    Jun 2012
    Location
    USA
    Posts
    5
    Rep Power
    0

    Default Finding middle value-entered in an array is producing inconsistent results

    Hello again everyone! Thanks for your help again earlier. I am making an array that compares each others' values by differences. I got the maximum and minimum value fine. But the median value, as in the middle value is not consistently read.

    It reads okay if the values I entered are 100, 500, 400. The middle value would be 400. Minimum value is 100, and maximum value is 500.
    It doesn't read right if I enter values that don't have the same digit lengths. Like, 1000, 500, 10. It displays the maximum and minimum value right, but the middle value reads the minimum value too. Instead of, max: 1000, mid: 500, min: 10 -- it reads max:1000, mid: 10, min:10.

    Java Code:
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.*;
    
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    /**
     *
     * @author Juneelyn
     */
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
          
            
            //Start array
                  
            System.out.println("\n Please enter name of first salesperson");
            
            String []Names = new String [3];
            double [] aryTotalSales = new double [3];
            
            Names[0] = getInput();
            
            System.out.println("\nPlease enter salesperson's total annual compensation");
            aryTotalSales[0]= captureDouble();
            
            
            System.out.println("\n Please enter name of second salesperson");
            Names[1] = getInput();
    
            System.out.println("\nPlease enter salesperson's total annual compensation");
            aryTotalSales[1]= captureDouble();
            
            
            System.out.println("\n Please enter name of third salesperson");
            Names[2] = getInput();
                    
            System.out.println("\nPlease enter salesperson's total annual compensation");
            aryTotalSales[2]= captureDouble();
    
             //Identify largest to smallest value.
             System.out.println("Maximum Value = " + getMaxValue(aryTotalSales));  
             System.out.println("Middle Value = " + median(aryTotalSales)); 
             System.out.println("Minimum Value = " + getMinValue(aryTotalSales));  
             
    
             //Compare earnings
             double dblmiddleEarner=getMaxValue(aryTotalSales) - median(aryTotalSales);
             System.out.println("Middle Earner needs"  +dblmiddleEarner+  "to match up highest earner.");
             double dblleastEarner=getMaxValue(aryTotalSales) - getMinValue(aryTotalSales);
             System.out.println("Least Earner needs"  +dblleastEarner+  "to match up highest earner.");
    
             
           
           
          
        }
      
         //Find maximum (largest) value in array using loop  
                    public static double getMaxValue(double[] aryTotalSales){  
                        double maxValue = aryTotalSales[0];  
                        for(int i=1;i<aryTotalSales.length;i++){  
                            if(aryTotalSales[i] > maxValue){  
                                maxValue = aryTotalSales[i];  
                            }  
                        }  
                        return maxValue;  
                    }
         //Find minimun (smallest) value in array using loop
                                public static double getMinValue(double[] aryTotalSales){  
                double minValue = aryTotalSales[0];  
                for(int i=1;i<aryTotalSales.length;i++){  
                    if(aryTotalSales[i] < minValue){  
                    minValue = aryTotalSales[i];  
                    }  
                }  
                return minValue;  
                }  
                    
                                public static double median(double[] aryTotalSales) {
                                    int middle = aryTotalSales.length/2;  // subscript of middle element
                                    if (aryTotalSales.length%2 == 1) {
                                        // Odd number of elements -- return the middle one.
                                        return aryTotalSales[middle];
                                    } else {
                                    // Even number -- return average of middle two
                                    // Must cast the numbers to double before dividing.
                                    return (aryTotalSales[middle-1] + aryTotalSales[middle]) / 2.0;
                                    }
                                }//end method median
                                        //Find middle value in array using loop
                   
                                
                 
    
            private static double captureDouble()
            {   //captures double values.
                String strInput = getInput();
    
                try
                {
                    Double dblInput = Double.parseDouble(strInput);
                    return dblInput;
                }
                catch (Exception e)
                {   //Prompts user that input is invalid.
                    System.out.println("Please enter valid double.");
                    return 0;
                }        
            }
       
               private static int captureInteger()
            {   //Captures integer value.
                String strInput = getInput();
    
                try
                {
                    int intInput = Integer.parseInt(strInput);
                    return intInput;
                }
                catch (Exception e)
                {
                    System.out.println("Please enter valid integer.");
                    return 0;
                }
            }
        
               private static String getInput()
            {   //Error handling.
                BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
                String inputData;
    
                try
                {
                    inputData = inputReader.readLine();
                    return inputData;
                }
                catch (IOException e)
                {
                    System.out.println("Error reading keyboard input");
                    return "";
                }
            }
        }
    WRONG RESULTS: On second thought, here I entered same digit/number length but it is not reading the middle value properly. :(

    Please enter name of first salesperson
    Al

    Please enter salesperson's total annual compensation
    500

    Please enter name of second salesperson
    Ed

    Please enter salesperson's total annual compensation
    200

    Please enter name of third salesperson
    Su

    Please enter salesperson's total annual compensation
    600
    Maximum Value = 600.0
    Middle Value = 200.0
    Minimum Value = 200.0
    Middle Earner needs400.0to match up highest earner.
    Least Earner needs400.0to match up highest earner.
    BUILD SUCCESSFUL (total time: 20 seconds)

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,259
    Rep Power
    25

    Default Re: Finding middle value-entered in an array is producing inconsistent results

    You need to do some debugging of the code to see why it is not doing what you want. One way to see what the code is doing is to add printlns that print out the values of variables as their values are changed and as they are used to control the program execution.

    A suggestion for testing: Hardcode the answers for all the questions for the case where the code gives the wrong results. That will make it very easy to do repeated tests without having to constantly type in data.
    Last edited by Norm; 06-29-2012 at 05:07 PM.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default Re: Finding middle value-entered in an array is producing inconsistent results

    First, I think you should write a better code for this:

    Java Code:
    System.out.println("\n Please enter name of first salesperson");
             
            String []Names = new String [3];
            double [] aryTotalSales = new double [3];
             
            Names[0] = getInput();
             
            System.out.println("\nPlease enter salesperson's total annual compensation");
            aryTotalSales[0]= captureDouble();
             
             
            System.out.println("\n Please enter name of second salesperson");
            Names[1] = getInput();
     
            System.out.println("\nPlease enter salesperson's total annual compensation");
            aryTotalSales[1]= captureDouble();
             
             
            System.out.println("\n Please enter name of third salesperson");
            Names[2] = getInput();
                     
            System.out.println("\nPlease enter salesperson's total annual compensation");
            aryTotalSales[2]= captureDouble();
    Use for example for loop so that you don't need to write everytime same part of code.


    My opinion for finding the middle element is:
    1. have some array of total annual compensations
    2. find min and max element of that array
    3. remove that elements from array
    4. do steps 2 and 3 on and on until you have left only 1 or 2 elements.
    5. if you have only 1 element left that's the middle one, but if you have 2 of them then you should choose which one to choose.

    But, probably the best way for finding middle element is to sort that array and return the element which index is in the middle of that sorted array.
    Last edited by cselic; 06-29-2012 at 05:14 PM.

  4. #4
    jpab29 is offline Member
    Join Date
    Jun 2012
    Location
    USA
    Posts
    5
    Rep Power
    0

    Default Re: Finding middle value-entered in an array is producing inconsistent results

    Thank you so much for all your suggestions!

    when removing the elements, is .pop useful? (no sleep for 20 hours haha)

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,259
    Rep Power
    25

    Default Re: Finding middle value-entered in an array is producing inconsistent results

    when removing the elements, is .pop useful
    What class are you talking about?
    If you don't understand my response, don't ignore it, ask a question.

  6. #6
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default Re: Finding middle value-entered in an array is producing inconsistent results

    Thank you so much for all your suggestions!

    when removing the elements, is .pop useful?
    Yes, it's useful. But I'm suggesting you that instead of using array for total annual compensation you should rather use ArrayList. ArrayList-s have more functionality and they are easier for coding.

    Here is one example of them: Java ArrayList : Generics & Sorting

    (no sleep for 20 hours haha)
    Attaboy.

  7. #7
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default Re: Finding middle value-entered in an array is producing inconsistent results

    I will give you a little example what ArrayLists are capable of:

    Java Code:
    import java.util.ArrayList;
    import java.util.Collections;
    
    public class MainArrayListeExample {
    	public static void main(String[] args) {
    		
    		ArrayList<Double> annualCompensation = new ArrayList<Double>();
    		
    		annualCompensation.add(27.33);
    		annualCompensation.add(33.2);
    		annualCompensation.add(54.22);
    		annualCompensation.add(32.11);
    		annualCompensation.add(12.56);
    		annualCompensation.add(43.99);
    		annualCompensation.add(24.29);
    		
    		//before removing element
    		for(int i=0; i< annualCompensation.size(); i++)
    		System.out.print(i + " = " + annualCompensation.get(i).toString() + "; ");
    		System.out.println();
    		
    		// We could remove any element when we want to. For example removing of the 4th element
    		annualCompensation.remove(3);
    		
    		// after removing 4th element
    		System.out.println("After removing the 4th element:");
    		for(int i=0; i< annualCompensation.size(); i++)
    			System.out.print(i + " = " + annualCompensation.get(i).toString() + "; ");
    		System.out.println();
    			
    	   // how to sort array list
    		Collections.sort(annualCompensation);
    		
    		System.out.println("Sorted list:");
    		for(int i=0; i< annualCompensation.size(); i++)
    			System.out.print(annualCompensation.get(i).toString() + ", ");
    		
    		// max element is the last element of sorted arrray list annualCompensation
    		// min element is the first element of sorted array list annualCompensation
    		// middle element is the middle element of sorted array list annualCompensation
    		
    		System.out.println();
    		System.out.println("min = " + annualCompensation.get(0));
    		System.out.println("max = " + annualCompensation.get(annualCompensation.size()-1));
    		System.out.println("middle = " + annualCompensation.get(annualCompensation.size()/2));
    		
    	}
    }

Similar Threads

  1. Trying to work out the middle number from an array
    By daemonlies in forum New To Java
    Replies: 2
    Last Post: 04-30-2012, 02:27 PM
  2. Finding MIddle number help
    By rosanator10 in forum New To Java
    Replies: 6
    Last Post: 02-01-2012, 12:55 AM
  3. Replies: 15
    Last Post: 06-22-2011, 07:47 PM
  4. Replies: 4
    Last Post: 11-05-2010, 10:43 AM
  5. Replies: 2
    Last Post: 09-06-2010, 01:03 AM

Tags for this Thread

Posting Permissions

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