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.

Similar Messages

  • 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.

  • In which table may I find the settled values from the WO's settlement

    Hello Expert,
    Can anyone be so kind an let me know In which table may I find  the value of settled costs from Work Order broken donwn into Settlement Receivers?
    I have found the table COBRB where I'm able to see the settlement rules for the WO but where the values from settlement are stored?
    Thank you in advance for valubale answers.
    Regards:
    Lukasz Kurlit

    Hello Kolla,
    I was too quick with my last answer, still I have the problem with this relation between COBRB and COEP, let me clarify it again.
    In WO I have manually modified the settlement rule that way that I settled costs split into two Cost Centers.
    Both lines regarding settlement rules are visible in table COBRB.
    Then I have  found in COEP table that there are stored exact values regarding settlement for both Cost Centers, one value for one Cost Center but without any key shows which one refers to which Cost Center (I recognized it after values which were settled in different time and after modification of settlement rule)
    What I need now is to find the relationship between COBRB and COEP that way that I will be able to know clearly (for reporting purpose) which line from COEP refers to which Cost Center recorded in COBRB.
    Link via OBJNR gives me only both lines in COEP without knowledge which one is from which Cost Center, there is no such field which will indicate which Cost center is hidden behind the value.
    I will be very appreciated for any hints how to find it.
    Regards:
    Lukasz Kurlit

  • Trying to find out how to get the smallest value in a 2-D array

    I figured out how to get the largest and smallest in a 1-D array, but I'm having trouble with the for loop for the 2-D array
    I can't seem to figure out how I can get it to check every element in the 2-D array
    Lets say I have this array
    int[][] aRay = new int[][] {{ 1, 2, 3} , {4, 5, 6 }};and I want to find the smallest value, I think I can figure out what goes in the box of the for loop I just need help with how I can check every element..
    Thanks all

    Ok so here's what i've got so far and my brain is starting to hurt,
    My output right now is "2".. i'm almost there :/ aren't I?
    public class bladddhd
         public static void main( String [] args )
         int[][] aRay = new int[][] {{ 1, 2, 3} , {4, 5, 6 }};
              int length2 = aRay[0].length;
              int temp = 0;
              for(int i = 0; i < aRay.length; ++ i)
                        if(aRay[0] > temp)
                             temp = aRay[0][i];
                        for(int j = 0; j < length2; ++j)
                                  if(aRay[1][j] < temp)
                                       temp = aRay[1][j];
                   System.out.println(temp);

  • 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 find out the duplicate value from each columns.

    I have below four columns,
    How can i find out the duplicate value from each columns.
    with All_files as (
    select '1000' as INVOICE,'2000' AS DELIVERYNOTE,'3000' CANDELINVOICE,'4000' CANDELIVERYNOTE from dual union all
    select '5000','6000','7000','8000' from dual union all
    select '9000','1000','1100','1200' from dual union all
    select '1200','3400','6700','8790' from dual union all
    select '1000','2000','3000','9000' from dual union all
    select '1230','2340','3450','4560' from dual
    SELECT * FROM All_files
    Output should be as per below.
    1000 2000 3000 4000
    9000 1000 1100 1200
    1200 3400 6700 8790
    1000 2000 3000 9000
    Required to check uniqueness in cross columns.
    Thanks.

    Try this (sorry about the formatting)...
    WITH all_files AS (SELECT   '1000' AS INVOICE,
                                '2000' AS DELIVERYNOTE,
                                '3000' CANDELINVOICE,
                                '4000' CANDELIVERYNOTE
                         FROM   DUAL
                       UNION ALL
                       SELECT   '5000',
                                '6000',
                                '7000',
                                '8000'
                         FROM   DUAL
                       UNION ALL
                       SELECT   '9000',
                                '1000',
                                '1100',
                                '1200'
                         FROM   DUAL
                       UNION ALL
                       SELECT   '1200',
                                '3400',
                                '6700',
                                '8790'
                         FROM   DUAL
                       UNION ALL
                       SELECT   '1000',
                                '2000',
                                '3000',
                                '9000'
                         FROM   DUAL
                       UNION ALL
                       SELECT   '1230',
                                '2340',
                                '3450',
                                '4560'
                         FROM   DUAL),
        t_base
           AS (SELECT      invoice
                        || ','
                        || deliverynote
                        || ','
                        || candelinvoice
                        || ','
                        || candeliverynote
                           str
                 FROM   all_files),
        t_str
           AS (SELECT   str || ',' AS str,
                        (LENGTH (str) - LENGTH (REPLACE (str, ','))) + 1
                           AS no_of_elements
                 FROM   t_base),
        t_n_rows
           AS (    SELECT   LEVEL AS i
                     FROM   DUAL
               CONNECT BY   LEVEL <=
                               (    SELECT   SUM (no_of_elements) FROM t_str)),
        t_build AS (SELECT   t_str.str,
                             nt.i AS element_no,
                             INSTR (t_str.str,
                                    DECODE (nt.i, 1, 0, 1),
                                    DECODE (nt.i, 1, 1, nt.i - 1))
                             + 1
                                AS start_pos,
                             INSTR (t_str.str,
                                    1,
                                    DECODE (nt.i, 1, 1, nt.i))
                                AS next_pos
                      FROM      t_str
                             JOIN
                                t_n_rows nt
                             ON nt.i <= t_str.no_of_elements),
        t_build2
           AS (SELECT   RTRIM (str, ',') AS original_string,
                        SUBSTR (str, start_pos, (next_pos - start_pos))
                           AS single_element,
                        element_no
                 FROM   t_build),
        t_build3
           AS (SELECT   single_element,
                        COUNT( * )
                           OVER (PARTITION BY single_element
                                 ORDER BY single_element)
                           ele_count
                 FROM   t_build2)
    SELECT   DISTINCT INVOICE,
                      DELIVERYNOTE,
                      CANDELINVOICE,
                      CANDELIVERYNOTE
      FROM   all_files, t_build3
    WHERE   ele_count > 1
             AND (   INVOICE = single_element
                  OR DELIVERYNOTE = single_element
                  OR CANDELINVOICE = single_element
                  OR CANDELIVERYNOTE = single_element)I think this will be faster than the previous solution?
    Cheers
    Ben
    Edited by: Munky on Feb 17, 2011 2:11 PM - "I think this will be faster than the previous solution?", nope - it's not :(

  • Finding the smallest letter in a single alphanumeric string

    How do I find the smallest letter in a single alphanumeric input?
    I already wrote and successfully tested the code that takes an alphanumeric string as input, separates the number from the alphabet, and creates a new alphabetic string. However, I'm unsuccesful in writting the code to find the smallest letter within the alphabetic string. I am almost certain that the easy answer is Arrays.sort, but I unsuccesfully tried writing the code to place the alphabetic string into an array. I researched compareTo, but I do not have another object to compare?! Any suggetsions?

    Ahh flaimbait - I'm sure I'll get criticized for this... but - while we are talking about time-to-market, etc...:
    The most important issue in development is to make sure that you understand the project requirements. The requirements in this situation were:
    Find the smallest character in a string.
    Given that, then any developer that goes through the trouble of looking up the sort APIs, etc... is not helping themselves - all they really needed to do was to write one line of code (as xxxx graciously posted):
    for (int x=0; x<foo.length(); x++) if (foo.charAt(i)<low) low=foo.charAt(x);I absolutely guarantee that any Java programmer could write the above faster than they could figure out how to split a string appart by characters, look up the arraysort API, etc...
    The arraysort functions are EXTREMELY efficient, and I would never suggest that someone re-implement them. The point here is that just because you've got a wrecking ball available, you can still use a hammer to drive a nail.

  • Get distinct values from plsql array

    Hi,
    I have declared a variable as below in plsql proc.
    type t_itemid is table of varchar2(10);
    inserted set of items in to this using a program
    now i want distinct values from that array how can i get it.

    I am using 9i so i cannot use set operator and more over my problem is that i am declaring the variable inside the plsql block . when i tried i am getting the below errors:
    SQL> r
    1 declare
    2 type t_type is table of varchar2(10);
    3 v_type t_type;
    4 begin
    5 v_type := t_type('toys','story','good','good','toys','story','dupe','dupe');
    6 for i in (select column_value from table(v_type)) loop
    7 dbms_output.put_line(i.column_value);
    8 end loop;
    9* end;
    for i in (select column_value from table(v_type)) loop
    ERROR at line 6:
    ORA-06550: line 6, column 41:
    PLS-00642: local collection types not allowed in SQL statements
    ORA-06550: line 6, column 35:
    PL/SQL: ORA-22905: cannot access rows from a non-nested table item
    ORA-06550: line 6, column 10:
    PL/SQL: SQL Statement ignored
    ORA-06550: line 7, column 22:
    PLS-00364: loop index variable 'I' use is invalid
    ORA-06550: line 7, column 1:
    PL/SQL: Statement ignored

  • Java API to read the Encrypted Values from Windows Registry settings

    Is there any Java API to read the Encrypted Values from Windows Registry settings ?
    My Java Application invokes a 3rd party Tool that writes the key/value to windows registry settings under : “HKLM\Software\<3rdparty>\dataValue”.
    This entry is in BINARY and encrypted with 3DES, using crypto API from Microsoft.
    3rd party software to encrypt the data stored in registry it
    either uses C++ code: and uses the call “CryptProtectData” and “CryptUnProtectData” or
    If it is a .NET (C#) it uses the call “Protect” or “UnProtect” from class “ProtectData” of WinCrypt.h from the library “Crypt32.lib.
    Note: The data is encrypted using auto-generated machinekey and there is no public key shared to decrypt the Encrypted data.
    Since the data is encrypted using auto-generated machinekey the same can be decrypted from a .Net / C++ application using CryptUnprotectData or UnProtect() API of WinCrypt.h from the library “Crypt32.lib.
    To know more about Auto-Generated MachineKey in Windows refer the links below
    http://aspnetresources.com/tools/machineKey
    http://msdn.microsoft.com/en-us/library/ms998288.aspx
    I need to find a way in Java to find the equivalent API to decrypt (CryptUnprotectData) and Microsoft will automatically use the correct key.
    But i couldn't find any informato related to Java APIs to enrypt or decrypt data using auto-generated machinekey.
    Is there a way to read the encrypted data from Windows regsitry settings that is encrypted using the Auto-Generated Machine Key ?
    Kindly let me know if Java provides any such API or mechanism for this.

    If the symmetric key is "auto-generated" and is not being stored anywhere on the machine, it implies that the key is being regenerated based on known values on the machine. This is the same principle in generating 3DES keys using PBE (password-based-encryption). I would review the documentation on the C# side, figure out the algorithm or "seed" values being used by the algorithm, and then attempt to use the JCE to derive the 3DES key using PBE; you will need to provide the known values as parameters to the PBE key-generation function in JCE. Once derived, it can be used to decrypt the ciphertext from the Regiistry in exactly the same way as the CAPI/CNG framework.
    An alternate way for Java to use this key, is to write a JNI library that will call the native Windows code to do the decryption; then the Java program does not need to know details about the key.
    That said, there is a risk that if your code can derive the key based on known seeds, then so can an attacker. I don't know what your applicatiion is doing, but if this is anything related to compliance for some data-security regulation like PCI-DSS, then you will fail the audit (for being unable to prove you have adequate controls on the symmetric key) if a knowledgable QSA probes this design.
    Arshad Noor
    StrongAuth, Inc.

  • 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);

  • 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

  • Passing values from method array to class array

    HELP!! Plz excuse any ignorance. Am a noob and have created an array within my class. I then try to alter those array values from inside one of the classes methods. When I try to access the new values from the class array, they don't exist. I think it's a duration/scope issue and am struggling to get around it. This is the only way I can implement the task required and would appreciate any advice you can thorw. cheers in advance.. =~D

    I suspect that you're altering an array passed as a parameter, rather than array that's a field of the instance, but as you didn't post any of your code, that can only be a guess.

  • Finding the missing number from the table

    I have vendor table with the following column, refvendor_id, the refvendor_id is a primary key in the table. the customer use the application to enter information to the vendor table using an interface
    created in Java. my question is how can I query the refvendor_id numbers that have been skipped by the customer when they enter information to the vendor table.
    refvendor_id is a varchar data type.
    for example
    refvenodr_id
    1
    2
    3
    5
    6
    9
    I would like to capture in my sql the refvendor_id that is skipped here.
    4,7,8
    select refvendor_id
    from  vendor

    I suggest to find the number values with a regular expression.
    Here is a modified version, that will only use the pure number refvendor_ids
    -- Test-Data:
    with vendor as
    select '1' refvendor_id from dual union all
    select '2' refvendor_id from dual union all
    select '3' refvendor_id from dual union all
    select '5' refvendor_id from dual union all
    select '6' refvendor_id from dual union all
    select '9' refvendor_id from dual union all
    select '10'  refvendor_id from dual union all
    select '12'  refvendor_id  from dual union all
    select 'A'  refvendor_id from dual
    -- Query:
    select rownum from dual connect by rownum <= (select max(to_number(refvendor_id)) from vendor where regexp_like(refvendor_id,'^[0-9]+$') )
    minus
    select to_number(refvendor_id) from vendor where regexp_like(refvendor_id,'^[0-9]+$')
    order by 1;(I produce output in number-format, because i want numeric ordering in output)
    Edited by: hm on 14.12.2010 13:32 :
    Of cause you can also use your restrictions, but I can't see if that are really only numbers:
    select rownum from dual connect by rownum <= (select max(to_number(refvendor_id)) from vendor where SUBSTR (refvendor_id, 1, 1) IN ('1', '2', '3', '4', '5', '6', '7', '8', '9') AND LENGTH (refvendor_id) < 5 )
    minus
    select to_number(refvendor_id) from vendor where SUBSTR (refvendor_id, 1, 1) IN ('1', '2', '3', '4', '5', '6', '7', '8', '9') AND LENGTH (refvendor_id) < 5 )
    order by 1;

  • 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.

Maybe you are looking for

  • FTE report tab is missing in the MSS Role

    Hi All, We have installed BP's of MSS in the portal and it is working fine.but some users are facing the below issue. User is unable to see FTE report tab in the MSS Role in the portal inspite of having all the roles related to the MSS and BI system.

  • Unable to create a new cluster on our domain

    Hi there, I am having difficulties creating a new server 2012 R2 failover cluster in our domain.  We have a working 2008 R2 cluster that has been running fine for years now. I have tried on different hardward with single nodes and multiple nodes when

  • ZoneInfoMappings is ignored

    I have a test and production server running Fedora Core 4, JDK 1.5.0.12, and Tomcat 5.5. On my test machine, the JRE finds the ZoneInfoMappings file correctly and all valid timezone IDs, including aliases, are found. If I rename the zi directory to s

  • Trouble with Dreamweaver Lauching

    I have run Dreamweaver for about 2 years. All of a sudden, it would not launch, but it WOULD register as a recently active Application in the "Recent Items" menu. If I then try to restart my computer, I have to force quit Dreamweaver -- even though,

  • 80GB Classic gone black while updating firmware

    Hopefully someone can help, while upgrading my 80GB Classic, the iPod completely stopped functioning. iTunes will not recognize the iPod and it will not turn on at all. I have tried and tried to reset it but to no avail. Is there a fix or do I have t