Finding the largest values of an array without using if condition

Hi,
I am trying to find the largest values of an array without using any if condition. Can any one tell me the solution for that..
Thanks

I am trying to find the largest values of an arrayThe 'S' to values suggests that you want not only the largest one, but multiple ones among the largest ones. The best way, I think, is to sort the array, so that its largest values are grouped topgether. If the type is already Comparable, the following single line does the job:
Collections.sort(myArray);After this, the last values of the array are the largest ones.
Jerome.

Similar Messages

  • Finding a minimum value in an array without using loops

    I can find a minimum value in an array using a loop, but I am unsure of how to do it without any type of of loop
    Here is what I have using a loop:
    // This method searches for the minimum value in an array
    public static int min(int a[]){
    int min = a[0];
    for(int i = 1; i < a.length; i++){
    if(a[i] < min){
    min = a;
    return min;
    How do I covert this to do the same thing, using no loops?
    Thank you for replies
    Edited by: kazmania on Feb 7, 2008 12:26 PM

    public class Test112 {
    public int recurse(int[] x, int i, int n)
    if (i==x.length-1) { return (x[i] < n) ? x[i] : n; }
    n = (n < x[++i]) ? n : x;
    return recurse(x, i, n);
    public static void main(String[] args) {
    int[] nums = {3, 1, 56, 2, 99, 34, 5, 78, -400, 2383, 201, -9, -450};
    Test112 t = new Test112();
    int min = t.recurse(nums, 0, nums[0]);
    System.out.println(min);

  • Write the sql query to find largest value in row wise without using   great

    write the sql query to find largest value in row wise without using
    greatest fuction?

    Another not so good way, considering you want greatest of 4 fields from a single record:
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (Select 100 col1,200 col2,300 col3,400 col4 from dual
      2  union select 500,600,700,800 from dual
      3  union select 900,1000,1100,1200 from dual
      4  union select 1300,1400,1500,1600 from dual
      5  union select 1700,1800,1900,2000 from dual
      6  union select 2100,2200,2300,2400 from dual
      7  union select 2800,2700,2600,2500 from dual
      8  union select 2900,3000,3100,3200 from dual)
      9  SELECT (CASE WHEN col1 > col2 THEN col1 ELSE col2 END) Max_value
    10  FROM
    11  (SELECT (CASE WHEN col1_col2 > col2_col3 THEN col1_col2 ELSE col2_col3 END) col1,
    12         (CASE WHEN col2_col3 > col3_col4 THEN col2_col3 ELSE col3_col4 END) col2,
    13         (CASE WHEN col3_col4 > col4_col1 THEN col3_col4 ELSE col4_col1 END) col3
    14  FROM
    15  (SELECT (CASE WHEN col1 > col2 THEN col1 ELSE col2 END) col1_col2,
    16         (CASE WHEN col2 > col3 THEN col2 ELSE col3 END) col2_col3,
    17         (CASE WHEN col3 > col4 THEN col3 ELSE col4 END) col3_col4,
    18         (CASE WHEN col4 > col1 THEN col4 ELSE col1 END) col4_col1
    19* FROM t))
    SQL> /
    MAX_VALUE
           400
           800
          1200
          1600
          2000
          2400
          2800
          3200
    8 rows selected.
    SQL> Edited by: AP on Sep 21, 2010 6:29 AM

  • Finding the largest value...

    Hi guys,
    I'm creating a method where it finds the largest value in a list of integers, using a loop. When it finds it, it's stored in the "max" and returns the "max".
    Here's the code...
        public Integer findMax()
            List<Integer> list = Arrays.asList(4,8,2,10,24);
            int max = 0;
            for(Integer i = 0 ; i < list.size() ; i++) {
                if(max == list.get(i))
                max = i;
            return max;
        }It complies, but when i run it, it doesn't actually get the largest value (which should be 24). It's still 0 when i Inspect it.
    Does anybody know where i'm going wrong with this?

    Well i went through the method and it seems to be printing 0 five times...
        public Integer findMax()
            List<Integer> list = Arrays.asList(4,8,2,10,24);
            int max = 0;
            for(Integer i = 0 ; i < list.size() ; i++) {
                if(max >= list.get(i))
                max = list.get(i);
                System.out.println(max);
            return max;
        }After looking looking through the API, i used the length, instead of size, but when i compile the program it says it can't find the method. Do you know what else i have to change or add in the code for it to compile?
    DrClap wrote:
    if(max == list.get(i)) Can you explain, in words, what this comparison was meant to do?I've edited that, because that's wrong.

  • Finding the smallest value from an array

    Hi there :)
    I started learning Java a few days ago and have now run into my first problem :p
    I am using Netbeans on Mac OS X.
    I need to find the smallest value from an array. So far I've had no luck. Any suggestions would be fantastic.
    The code so far:
    * Math Problems
    * Created on May 4, 2007, 10:54 AM
    * PROJECT 1: - IN PROGRESS
    * Create a program that allows you to create an integer array of 18 elements with the following values
    * 3, 2, 4, 5, 6, 4, 5, 7, 3, 2, 3, 4, 7, 1, 2, 0, 0, 0
    *  - The program computes the sum of elements 0 to 14 and stores it in element 15                              // COMPLETED
    *  - The program computes the average and stores it in element 16                                              // COMPLETED
    *  - The program finds the smallest value from the array and stores it in element 17
    * PROJECT 2: - TO DO
    * Write a program that accepts from the command line and prints them out. Then use a for loop to print
    * the next 13 numbers in the sequence where each number is the sum of the previous two. FOR EXAMPLE:
    *  - input>java prob2 1 3
    *  - output>1 3 4 7 11 18 29 47 76 123 322 521 843 1364
    * PROJECT 3: - TO DO
    * Write a program that accepts from the command line two numbers in the range from 1 to 40. It then
    * compares these numbers against a single dimension array of five integer elements ranging in value
    * from 1 to 40. The program displays the message BINGO if the two inputted values are found in the array
    * element. FOR EXAMPLE:
    *  - input>java prob3 3 29
    *  - output>Your first number was 3
    *  -        Your second number was 29
    *  -        Its Bingo!  // This message if 3 and 29 are found in the array
    *  -        Bokya!      // This message if 3 and 29 are not found in the array
    *  -        The array was 7 5 25 5 19 30
    * PROJECT 3 EXTENSION: - OPTIONAL
    * Generate the array of 5 unique integers using random numbers
    package mathproblems;
    * @author Mohammad Ali
    public class Main {
        /** Creates a new instance of Main */
        public Main() {
         * @param args the command line arguments
        public static void main(String[] args) {
            int A[]={3,2,4,5,6,4,5,7,3,2,3,4,7,1,2,0,0,0};
            int O = A.length - 3;
            int B = A[0] + A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8] + A[9] + A[10] + A[11] + A[12] + A[13] + A[14];
            A[15] = B;  // Stores the sum of the integers in A[15]
            int C = B / O;
            A[16] = C;  // Computes and stores the average in A[16]
            int D = 101;
                if (A[0] < A[1]) { D = A[0]; }
                else { D = A[1]; }
                if (A[1] < A[2]) { D = A[1]; }
                else { D = A[2]; }
            System.out.println("There are " + O + " numbers in the Array");
            System.out.println("Those numbers add up to " + B + ".");
            System.out.println("The average of those numbers is " + C + ".");
            System.out.println("The smallest value in the array is " + D + ".");
    }The code is incomplete, but it works so far. The problem is I know there must be an easier way. SAVE ME :)

    OK :)
    Just thought I should show you the output as to help anyone else with the same problem:
    * Math Problems
    * Created on May 4, 2007, 10:54 AM
    * PROJECT 1: - IN PROGRESS
    * Create a program that allows you to create an integer array of 18 elements with the following values
    * 3, 2, 4, 5, 6, 4, 5, 7, 3, 2, 3, 4, 7, 1, 2, 0, 0, 0
    *  - The program computes the sum of elements 0 to 14 and stores it in element 15                              // COMPLETED
    *  - The program computes the average and stores it in element 16                                              // COMPLETED
    *  - The program finds the smallest value from the array and stores it in element 17                           // COMPLETED
    * PROJECT 2: - TO DO
    * Write a program that accepts from the command line and prints them out. Then use a for loop to print
    * the next 13 numbers in the sequence where each number is the sum of the previous two. FOR EXAMPLE:
    *  - input>java prob2 1 3
    *  - output>1 3 4 7 11 18 29 47 76 123 322 521 843 1364
    * PROJECT 3: - TO DO
    * Write a program that accepts from the command line two numbers in the range from 1 to 40. It then
    * compares these numbers against a single dimension array of five integer elements ranging in value
    * from 1 to 40. The program displays the message BINGO if the two inputted values are found in the array
    * element. FOR EXAMPLE:
    *  - input>java prob3 3 29
    *  - output>Your first number was 3
    *  -        Your second number was 29
    *  -        Its Bingo!  // This message if 3 and 29 are found in the array
    *  -        Bokya!      // This message if 3 and 29 are not found in the array
    *  -        The array was 7 5 25 5 19 30
    * PROJECT 3 EXTENSION: - OPTIONAL
    * Generate the array of 5 unique integers using random numbers
    package mathproblems;
    * @author Mohammad Ali
    import java.util.Arrays;
    public class Main { 
        /** Creates a new instance of Main */
        public Main() {
         * @param args the command line arguments
         public static void main(String[] args) {
                  int A[]={3,2,4,5,6,4,5,7,3,2,3,4,7,1,2,0,0,0};
              Arrays.sort(A);
              System.out.println("The smallest value in the array is " + A[0] + ".");
              int num = A.length;
              System.out.println("There are " + num + " values in the Array.");
              int sum = 0;
              for (int i = 0; i < A.length; i++) {
                   sum+=A;
              System.out.println("Those numbers add up to " + sum + ".");
              double d = (double)sum/num;
              System.out.println("The average value of those numbers is " + d + ".");
    What Iearned:
    1) How to create for loops properly
    2) How to import java.util.Arrays ( =D )
    3) How to get a more accurate average using double instead of int
    4) This forum is the best and has very helpful people 24/7 ( =D)
    Thanks Again,
    Mo.

  • How do I find the closest value to a constant in an array

    I have an array of floating numbers and I want to find a value in that array that is closest to a floating constant.     For example if I have the array 5.9, 2.8, 3.7, 5.8, 6.9, and if I have the constant 5.4, how would I find the closest value to 5.4 in the array, which in this case would be 5.8. The only approach I can think of is to subtract each value in the array from 5.8 and find the minimum value of an array which would be created from the differences. Is there a better approach?
    Thank you.

    Just be sure to take the absolute value of the difference and your proposed method is fine.

  • How to find the nearlest value in 1-D array ?

    Hi.. everybody..
    I need to seperate the raw data(1-D) into 2 group of array by the center value and then make the average value in each array. But I also still have the problem about if the center value is not the same of some value in the 1-D array. I cannot use the split function.
    "How to find the nearlest value to the center point that I calculated, in the 1-D array ?"
    Thanks a lot for anybody help

    In a general sense, since I'm not sure what your data values are or how far away your calculated center is from the true value, I would do it one of two ways:
    1) Use a threshold value and scan the array until the threshold is reached (assumes constantly increasing values in the array).
    2) Use either a) round to nearest integer b) round to + Infinity (round up) or c) round to - infinity (round down). If you don't have decimal values, you'll have to devide the values by a power of 10.
    2006 Ultimate LabVIEW G-eek.

  • How do you create an array without using a shell on the FP?

    I want to be able to read the status of front panel controls (value, control box selection, etc.) and save it to a file, as a "configuration" file -- then be able to load it and have all the controls set to the same states as were saved in the file. I was thinking an array would be a way to do this, as I have done that in VB. (Saving it as a text file, then reading lines back into the array when the file is read and point the control(s) values/states to the corresponding array element.
    So how do I create an array of X dimensions without using a shell on the front panel? Or can someone suggest a better way to accomplish what I am after? (Datalogging doesn't allow for saving the status by a filename, so I
    do not want to go that route.)

    Thanks so much m3nth! This definitely looks like what I was wanting... just not really knowing how to get there.
    I'm not sure I follow all the icons. Is that an array (top left with 0 constant) in the top example? And if so, that gets back to part of my original question of how to create an array without using a shell on the FP. Do I follow your diagram correctly?
    If I seem a tad green... well I am.
    I hope you understand the LabVIEW environment and icons are still very new to me.
    Also, I had a response from an NI app. engineer about this problem. He sent me a couple of VI's that he threw together approaching this by using Keys. (I still think you are pointing to the best solution.) I assume he wouldn't mind m
    e posting his reply and the VI's for the sake of a good, thorough, Roundtable discussion. So here are his comments with VI's attached:
    "I was implementing this exact functionality this morning for an application I'm working on. I only have five controls I want to save, but they are all of different data types. I simply wrote a key for each control, and read back that key on initialization. I simply passed in property node values to the save VI at the end, and passed the values out to property nodes at
    the beginning. I've attached my initialize and save VI's for you to view. If you have so many controls that this would not be feasible, you may want to look into clustering the controls and saving the cluster as a datalog file.
    Attachments:
    Initialize_Settings.vi ‏55 KB
    Save_Settings.vi ‏52 KB

  • How to use my findTheHighest method to find the highest value in my two dim

    I am going to create a 13row by 10 colume two dimensional array.
    how to use my findTheHighest method to find the highest value in my two dimensional array.
    .When i compile this program , i got those as following;
    "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsExce
    at TaxEvolution.findTheHighest(TaxEvolution.java:31)
    at TaxEvolutionClient.main(TaxEvolutionClient.java:25)"
    public class TaxEvolution{
    public double[][] salesTaxRates;
    public TaxEvolution()
      salesTaxRates = new double[13][10];
      fillProvinTaxRates();
    private void fillProvinTaxRates()
      for ( int row = 0; row < salesTaxRates.length; row++ )
        for ( int column = 0; column < salesTaxRates[row].length; column++ )
          salesTaxRates[row][column]= (int)(Math.random()*5000) + 1;
    public double findTheHighest()
        double highest = salesTaxRates[0][0];
        for ( int row = 0; row <= salesTaxRates.length; row++ )
          for ( int column = 0; column <= salesTaxRates[row].length; column++ )
             if ( salesTaxRates[row][column] >= highest )
                   highest = salesTaxRates[row][column];
        return highest;   
    public double[][] arrayTaxEvolution()
      double[][] returnTaxRates = new double[13][10];
      for ( int row = 0; row < salesTaxRates.length; row++ )
        for ( int column = 0; column < salesTaxRates[row].length; column++ )
          returnTaxRates = salesTaxRates;
      return returnTaxRates;
    public class TaxEvolutionClient{
    public static void main( String[] args ){
      TaxEvolution protaxRateList = new TaxEvolution();
      double[][] taxRateList = protaxRateList.arrayTaxEvolution();
        for ( int i = 0; i < taxRateList.length; i++ )
          for ( int j = 0; j < taxRateList[0].length; j++ )
            System.out.print( taxRateList[i][j] + "\t" );               
            System.out.print( protaxRateList.findTheHighest + "\t" );
    }

    Multiposted
    http://forum.java.sun.com/thread.jspa?threadID=699057&tstart=0

  • 1d cluster array replace value in a 1d boolean array (without using Loop)

    Hi ,
    is there a way to replace the values (string , boolean) ​​of a 1D array Cluster with value of 1D boolean array without using loop ?
    Regards
    Simone
    Attachments:
    111.png ‏75 KB

    Replace Array Subset requires that the array elements are type compatible with the elements that you want to replace. That seems not the case in your example.
    And the For Loop is anything but slow. How many billion elements do you expect your array to have to worry about performance of the for loop? With the type definition of your example even a ready made LabVIEW function would have to do internally a for loop too, since the boolean data inside the original array can not be in a continous memory area.
    Maybe if you show us what you try to do with the for loop we can understand better what your concerns are. As it is from the front panel image alone it is really hard to understand what your imagined problem might be.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • How to find the RGB Values of a Color for Hyperion

    When customizing your Hyperion forms, we come across situations where we need the exact RGB value of a given color. This article explains a simple technique to find the RGB values using MS Paint and the Calculator applications that come as standard applications with your operating system.
    Here are the steps to find the exact RGB value of a given color.
    1) View your Hyperion form using IE, scroll down until you see the color you want to find the RGB value and press the "Print Screen" button (in your keyboard).
    2) Open MS Paint and click Edit -> Paste or simply Ctrl+V. What you saw in the browser will be copied as a new untitled image.
    3) Select the Color Picker tool and click on an area that has the color you want to match.
    4) Now go to Edit Colors... option and click on the "Define Custom Colors >>" button. The color you picked will be selected on this palette. At the bottom right hand corner you will see the Red, Green and Blue values you need. Note down the R,G,B values (given in decimal).
    5) Now we need to find out the hexa-decimal values that correspond to those decimal values. This is where we use the simple Calculator. Open the Calculator application from Program -> Accessories. Switch to the scientific mode by clicking View ->Scientific.
    6) By default it will be in the decimal number mode. Enter the R value (238 in this example) and click on the Hex radio button. The corresponding hexa-decimal value (EE in this case) will be shown in the dial.
    The selected color in this case has the same value for R, G and B. (In fact, all shades of gray has the same values for R, G and B.) Therefore, the RGB value of the background color that we need is #eeeeee. Repeat step 6 to find out the hex value for the Green and Blue elements, if they are different.
    Tip:
    If you find it difficult to pick a color, zoom the image by pressing Ctrl+PageDown or using View -> Zoom -> Custom... option.

    These tips are to find the RGB color of HFM default row where row is text and text lines in data columns are also visible to business users as Yellow as an input cell. By applying the same RGB color you can apply the same color to your data cells or rows. This post shows how to identify color from any web view-able object.
    Regards,
    Manaf

  • How to find the PREVIOUS value of a non-DB item?

    I want to do a simple thing but found it impossible.
    I want to find the previous value of a non-DB item in a form.
    I tried creating a text item and populating it using PRE-TEXT-ITEM but that does not work.
    WHEN-VALIDATE-ITEM does not work either because WVI fires only after item value has changed.
    Any suggestions will be greatly appreciated.
    Edited by: Channa on Apr 2, 2010 4:34 AM

    Channa wrote:
    I want to do a simple thing but found it impossible.
    I want to find the previous value of a non-DB item in a form.
    I tried creating a text item and populating it using PRE-TEXT-ITEM but that does not work.
    WHEN-VALIDATE-ITEM does not work either because WVI fires only after item value has changed.
    Any suggestions will be greatly appreciated.
    Edited by: Channa on Apr 2, 2010 4:34 AMPlease make it clear what is your requirement then possibly we can provide you a better answer
    You can use Global variables for to store old values also on Post-query populate a value in separate field or Parameter

  • Recursion:returning the largest value in a linked list

    import java.io.*;
    import java.util.*;
    class Node{
         int num;
         Node next;
         Node(int n){
              num = n;
              next = null;
    class RecursivePrint{
         public static void main(String[] args){
              Node np, last;
              Node top = null;
              last = null;
              for(int i = 1; i <11; i++){
                   np = new Node(i);
                   if(top==null)top = np;
                        else
                   last.next = np;
                   last = np;
              int x =Largest(top);
             System.out.println("large is "+ x);
         }//end main
         public static int Largest(Node top){
              int large = 0;
              if(top==null){
                   return 0;
                   while(top!=null){
               if(top.num > large){
                   large = top.num;
                   //top = top.next;
              Largest(top.next);     
         }//while
         return large;
    }//end class
    I am trying to return the largest value in a linked list (10) in this case.  when I do it withour recurrsion it works ok, but when I try it with recurrsion it dies.  The logic seems ok to me, cannot figure why it dies.

    chetah wrote:
    public static int Largest(Node top){
              int large = 0;
              if(top==null){
                   return 0;
              if(top.num > large){
                   large = top.num;
                   //top = top.next;
                   Largest(top.next);
         return large;
    Initially I had the above, it return only 1 that was the reason for puting the loop.You don't seem to understand recursion or variable scope.
    int large = 0;large is a different variable inside each instance of the method.
    So when you get back up to the value 1 from the recursive calls its just comparing 1 to 0
    Here's a solution...
         public static int Largest(Node top){
              if(top.next != null){
                   if(Largest(top.next) > top.num)
                        return Largest(top.next);}
              return top.num;
         }

  • Finding the min value in a hashtable

    Hi,
    I'm trying to work out the lowest value contained in a hashTable. So far I've got.
    import java.util.Enumeration;
    import java.util.Hashtable;
    import java.util.Vector;
    public class StoreValuesDouble extends Statistic {
          * Each object of the class (StoreValuesDouble) will have these attributes.
          * When you call the StoreValuesDouble class you can use
          * myDoubleValues (a Vector holding Double types),
          * Hashtable (a Hashtable using Double types as values and keys) and
          * nullValues (an Double currently set to 0.0).
         Vector<Double> myDoubleValues; //declare a variable myDoubleValues that is of data type Vector
         Hashtable<Double, Double> myValues; //declare a variable myvalues that is a data type Hashtable
         Double nullValues = 0.0; //Double attribute to count the number of null values contained in the vector
          * pass myDoubleValues to inValues
          * @param Vector /<Double/> a vector holding Double values
          * @param inValues the values in the vector
          * @return
         public void DoubleStat(Vector<Double> inValues) {
              myDoubleValues = inValues;
          * calculate the mean of myDoubleValues
          * @return mean of myDoubleValues as a double
         public double meanDouble() {
              double mean = 0;
              Double currentDouble;
              double nonNull = 0;
              for (double j = 0; j < myDoubleValues.size(); j++)
                   currentDouble = myDoubleValues.elementAt((int) j);
                   if (currentDouble != null) {
                        mean += currentDouble.doubleValue();
                        nonNull++;
              return mean / nonNull;
          * calculate the standard devitation of myDoubleValues
          * @return standard devitation of myDoubleValues as a double
         public double standardDeviationDouble() {
              double m = meanDouble();
              double t = 0.0;
              Double currentDouble;
              double n = 0;
              for (double j = 0; j < getDoubleValues(); j++) {
                   currentDouble = myDoubleValues.elementAt((int)j);
                   if (currentDouble != null) {
                        n = currentDouble.doubleValue();
                        t += (n - m) * (n - m);
              return Math.sqrt(t / (myDoubleValues.size() - 1.0));// n - 1 as sample varience
          * return the number of values of myDoubleValues to help calculate the mean & standard deviation
          * @return the size of myDoubleValues as a Double
         public double getDoubleValues() {
              return myDoubleValues.size();
          * compute the number of null values
          * @return a double value representing the number of null values
         public Double getDoubleNull() {
              Double nbNull = 0.0;
              // test if myIntValues is null
              if (myDoubleValues == null) {
                   System.out.println("Please enter values that are not null!");
                   return 0.0;
              // if not null, parse all values
                   // for each value, test if it is null or not
                   Double currentDouble;
                   for (double i = 0; i < myDoubleValues.size(); i++) {
                        currentDouble = myDoubleValues.elementAt((int)i);
                        if (currentDouble != null) {
                             /// nothing to do
                        else {
                             nbNull++;
              return nbNull;
    //find the MIN values in the Hashtable to give us the range (with the MAX value)
         public Double MinDouble()
              Double MinDouble = null;
              Double currentValue;
              for (double j = 0; j < myDoubleValues.size(); j++)
                   currentValue = myDoubleValues.elementAt((int) j);
                   if (currentValue != null){
                   if (currentValue <= MinDouble) {
                        MinDouble = currentValue;
              return MinDouble;
         /*find the MAX value in the Hashtable to give us the range (with the MIN value)
         public double MAX()
          * Create an instance of StoreValuesDouble to hold vector values and number of times the values
          * appear. StoreValuesDouble automatically contains the variables defined above
          * (myDoubleValues, myValues and nullValues) we have to initialise myDoubleValues and myValues
          * as they have been defined but not initialised. nullValues has been defined (int) and initialised (0).
          * @param Vector /<Double/> a vector holding Double values
          * @param inValues the values in the vector
          * @return
         public StoreValuesDouble(Vector<Double> inValues) {
              myDoubleValues = inValues; //the attribute myDoubleValues defined in the StoreValuesDouble class
              //is the inValues parameter, this allows us to store the Vector in inValues
              myValues = new Hashtable<Double, Double>(); // create an instance of/initialise Hashtable
          * Now define the methods to make the instance StoreValuesDouble do what we want it to do
          * (ie parse all the double values of the myDoubleValues Vector attribute.
         public void computeDoubleValues() {
              Double currentDouble;//local variable to store the current read Double object
               * Use a for loop to read through all the values contained in the vector
              for (double i = 0; i < myDoubleValues.size(); i++) {
                   currentDouble = myDoubleValues.elementAt((int)i);
                   //currentDouble is now the Double object stored at i
                   //to check that i is not null we use the if statment
                   if (currentDouble != null) {
                        //i is not null so we want to add it to the hashtable. Rather than writing a lot of code
                        //here to do checking and adding we just call a method that can be written seperately
                        updateDoubleTable(currentDouble);
                   else {
                        //i is null so we just count it by adding it to our nullValues attribute
                        nullValues++;
          * Update the current distribution of Doubles
          * @param Double for the value of the key
          * @param inDouble for the value entered into the Hashtable (the object)
         public void updateDoubleTable(Double inDouble) {
              //First test that variable inDouble is not null
              if (inDouble != null) {
                   //update the table myValues this involves two tasks
                   //1)see if the double object has already been seen
                   //so we create a local variable to test the Hashtable
                   boolean alreadyPresent;
                   alreadyPresent = myValues.containsKey(inDouble);
                   //here we check whether inDouble is already in myValues
                   if (alreadyPresent) {
                        //if it is present we need to increase the counter
                        Double counter = myValues.get(inDouble);
                        //local variable counter to get the value associated to the key inDouble
                        Double newCounter = new Double(counter.intValue() + 1.0);
                        //update counter values and then ...
                        myValues.put(inDouble, newCounter);
                        //put into myValues
                        //as Hashtable can store only Objects, we cannot use primitive types
                        // so we use Objects related to primitive types as Integer, Float, Double
                        // or Boolean (here, we use Double)
                   } else {
                        //store the double and set it's counter to 1
                        myValues.put(inDouble, new Double(1));
              } else {
                   //do nothing
         //now we want to display the values
         public void displayDoubleTable() {
              // to display the distribution, we need to parse all the keys of the
              // hashtable and access to the value associated to each key
              Enumeration<Double> keys = myValues.keys();
              Double currentKey;
              Double currentValue;
              System.out.println("");
              System.out.println("Hashtable Information:");
              System.out.println("");
              System.out.println(myDoubleValues.size() + " Double objects in initial vector");
              System.out.println("");
              while (keys.hasMoreElements()) {
                   currentKey = keys.nextElement();
                   currentValue = myValues.get(currentKey);
                   System.out.println("The value " + currentKey.doubleValue()
                             + " has been seen " + currentValue.doubleValue()
                             + " time(s) in the initial Vector");
              System.out.println("");
              System.out.println("There were " + nullValues
                        + " null Double object(s) in the inital Vector");
         }As part of the StoreValuesDouble class. And to display it.
    package statistics;
    import java.util.Vector;
    public class TestStatDouble {
         static Vector<Double> doubleVector;
          * Create and initialise a vector of values and compute the mean,
          * standard deviation, distribution and MIN/MAX values.
         public static void main(String[] args) {
               // initialise the values in initValues
              initValues();
              // create an instance of StoreValuesDouble taking double as the parameter
              StoreValuesDouble is = new StoreValuesDouble(doubleVector);
              //Display the results
              displayVectorContent(doubleVector);
              System.out.println("");
              System.out.println("Number of null values: " + is.getDoubleNull());
              System.out.println("Number of non-null values is: " +(is.getDoubleValues() - is.getDoubleNull()));
              System.out.println("Number of all values: " + is.getDoubleValues());
              System.out.println("The mean is: " + is.meanDouble());
              System.out.println("Standard deviation is: " + is.standardDeviationDouble());
              System.out.println("The lowest value is " + is.MinDouble());
              System.out.println("");
               * now I want to display the results from the displayTable method in the StoreValuesDouble
               * class so I create an instance of StoreValuesDouble and use the computeDoubleValues and
               * displayDoubleTable methods.
              StoreValuesDouble storeValues = new StoreValuesDouble(doubleVector);
              storeValues.computeDoubleValues();
              storeValues.displayDoubleTable();
          * create the class method initValues() to add values to the Vector doubleVector
         public static void initValues()
              doubleVector = new Vector<Double>();
              doubleVector.addElement(null);
              doubleVector.addElement(new Double(10.9));
              doubleVector.addElement(new Double(15.95));
              doubleVector.addElement(new Double(17));
              doubleVector.addElement(null);
              doubleVector.addElement(new Double(1));
              doubleVector.addElement(new Double(4));
              doubleVector.addElement(new Double(10.499));
              doubleVector.addElement(null);
              doubleVector.addElement(new Double(10.4999));
              doubleVector.addElement(new Double(17));
              doubleVector.addElement(new Double(-15));
              doubleVector.addElement(null);
              doubleVector.addElement(new Double(14));
              doubleVector.addElement(new Double(20));
              doubleVector.addElement(new Double(-3));
              doubleVector.addElement(null);
              doubleVector.addElement(new Double(9));
              doubleVector.addElement(new Double(1.5));
              doubleVector.addElement(null);
              doubleVector.addElement(new Double(10.22));
              doubleVector.addElement(new Double(15.23));
              doubleVector.addElement(new Double(17.91));
              doubleVector.addElement(null);
          * class method to print values contained in the vector doubleVector to the console.
          * @param doubleVector the Vector to be displayed
         public static void displayVectorContent(Vector doubleVector)
              Double currentDouble;
              System.out.println("Double values within the Vector:");
              for (int i=0; i<doubleVector.size();i++)
                   try
                        currentDouble = (Double) doubleVector.elementAt(i);
                        if (currentDouble != null)
                             System.out.print(currentDouble.toString() + " ");
                   catch(ClassCastException cce)
                        System.out.print(cce.getMessage() + " ");
                        cce.printStackTrace();
              System.out.println("");
         It compiles fine but when I try and run it I get a
    Exception in thread "main" java.lang.NullPointerException
         at statistics.StoreValuesDouble.MinDouble(StoreValuesDouble.java:139)
         at statistics.TestStatDouble.main(TestStatDouble.java:37)
    TestStatDouble 37 is
    System.out.println("The lowest value is " + is.MinDouble());139 is
    if (currentValue <= MinDouble) {I guess the problem's in my if loop but I'm not sure why. Any help would be appreciated.
    Message was edited by:
    Ali_D

    Couple of points about your code:
    1. Don't declare your instance variables as solid types, declare them using their interfaces (where applicable), so in your case don't specifiy that you are using Vector or Hashtable, use List and Map. This will allow you to easily change your code to use a different collection, if and when appropriate. Also the unnecessary overhead of Vectors synchronisation means that you should use ArrayList instead of vector (that means that you will have to use get(int) instead of elementAt() but that's a very small price to pay.
    2. Declare local variables as close to their point of usage as possible. (Unless you need to do this for your course work, in which case you don't have a choice).
    3. Use the appropriate data type. For your count of null values you should be using an int or a long (you can't have a fractional count value!) Also, this should have been obvious to you, when you had to cast the value to an int for use with your lists. (Using double as an index is a very bad idea... And before you go posting the question, do a search on why floating point precision may not give you the results you expect)
    4. Code defencively... e.g. in your meanDouble() method, you set nonNull to 0, and then you do a division using that value. What do you think is going to happen if your loop doesn't execute once? Division by zero... You should handle these cases, rather than letting them fail ignominiously.
    5. If you are doing code like this...    if (currentDouble != null) {
            // / nothing to do
        } else {
            nbNull++;
        } Why have the empty block? You should just do the inverse.
        if (currentDouble == null) {
            nbNull++;
        } Far simpler, and expresses exactly what you are trying to do, not what you are not trying to do.
    6. Enumeration --- What version of java is that course being run in? I can see that you are using autoboxing, so it has to be 1.5 so, WHY is your lecturer encouraging the use of Vectors, Hashtables, and Enumerations!?!?!
    Anyway, that should be enough to be going on with.

  • FINDING THE LARGEST NODE IN A BINARY TREE

    can anybody help me with a recursive function to find the LARGEST NODE IN A BINARY TREE if you are given the following specs. PLEASE NOTE THAT IT'S A BINARY TREE NOT A SEARCH TREE.
    Public class Node {
    Node left;
    Node right;
    int val;
    int Largest(Node r){
    }

    Naah, just studying and thinking it's an interesting
    task Well, I diagree.
    since each time the recursive function is
    called, variables you hve in the method will be over
    written with the new recursive call.So what? For variables that are valid inside the scope of the method: that's how it supposed to be. Vor variables with a larger scope: hand them over as an additional argument.

Maybe you are looking for

  • Need help properly formating hard disk. hard disk model wd7500bpvt says no bootable drive.

    bought this hard disk new from hp about 3 or 4 months ago.  hard disk was not recognized by the laptop.  i download app from hp to do low level format on hard disk.  Then i formated the drive during windows vista installation.  Upon completion of win

  • IMac wont boot up

    My IMac wont boot up! I installed the Mac OSX system disk and ran disk utility this is the results: invalid node structure The volume Macintosh HD needs to be repaired. Error: Filesystem verify or repair failed. What do I do to get this up and runnin

  • Ipad air cant sign in imessage and facetime for ios 8.1.2

    Hi Before I make this topic, I read a lot of topics about the same problem as mine and I cant fine any solution. So my problem is: after updating to 8.1.2 for my ipad air, I have to sign in my imessage and facetime again and it says: "Imessage or Fac

  • Marketing Fonts in Document

    Marketing wants to send out .pdf documents that have company specific fonts in them. If I try to do that in .pdf, the fonts will not be viewable by our intended customers. Is there a way to embed the font in the document such that it is viewable by t

  • Had to restore iPad2 from itunes after IOS8 update with no option to restore from icloud backup.

    since i lost everything on my ipad due to the IOS8 update, i thought i'd try to do a manual restore from my icloud backup, but the only backup listed is one from the day i did the update/restore. i'm pretty sure it's not going to help me recover ever