Array count

hi everyone,
i'm just new to programming and i need some help from everyone that is willing to help me.
what's the statement or code that's counting the values of an array?how can you do it?
lets say i got 6 arrays and each has a diferent integer value.how can i write the code for having the totalvalue of the array?...keeping in mind that also there is into a for statement .....???.....

lets say i got 6 arrays.....I hardly call this clearly defined. It seems the OP was simply using that as an example.
You should always write code that will work for all situations. What if the requirements were changed so that the array needed to hold 10 numbers, wrong answer calculated. Or worse if the array was < 6 numbers long, ArrayIndexOutOfBounds error. Or maybe the code needs to be dynamic ie the user enters a value for how many numbers are to be held in the array. All these will fail with your hard coded 6.

Similar Messages

  • Can i use array.count in line?

    All,
    I have one small oracle program that take a ',' separated string as an input
    and assigns the individual string to a nested table.
    I am wondering if I can directly use array.count in my sql below
    instead of assigning the count of the array 1st and then
    using it.
    l_cause_codes_array := util_pkg.tokenize_string(p_cause_codes_csv, ',');
    l_count := l_cause_codes_array.count;
    My current sql:
    delete from po_complaint_cause p
    where p.po_number = p_po_number
    and p.comp_code = p_comp_code
    and l_count > 1;
    I would like to do something like:
    delete from po_complaint_cause p
    where p.po_number = p_po_number
    and p.comp_code = p_comp_code
    and l_l_cause_codes_array.count> 1;
    I just want to reduce one context switch if possible.
    Thanks.

    Hi,
    did it give an error? Did you try? But it is possible.
    But why not the next code:
      l_cause_codes_array := util_pkg.tokenize_string(p_cause_codes_csv, ',');
      if l_cause_codes_array.count >1
      then
        delete from po_complaint_cause p
        where p.po_number = p_po_number
        and p.comp_code = p_comp_code
      end if;Do only the delete if it is bigger than 1, that is I think the fastest switch.
    Herald ten Dam
    http://htendam.wordpress.com

  • Need help for array counting

    Any help for array question
    Hello to All:
    I want to tally or count some of the elements that I have in array but not sure how.
    I have for example: int myArray[] = {90,93,80,81,71,72,73,74};My objective is to tally all of the 90's, tally all of the 80's and tally all of the 70's.
    So, the result that I want to have would look something like the following:
    System.out.println ("The total tally number of 90's is " 2 );
    System.out.println ("The total tally number of 80's is " 2 );
    System.out.println ("The total tally number of 70's is " 4 );I do not want to add these numbers, just want to count them.
    Also I want to use a "forloop" to achieve the result intead of just declaring it at 2 or 4 etc..
    Any help Thankyou

    [u]First , This is not exactly what I have to
    do for homework. There is a lot more, a lot more
    involved with the program that I am working on.
    Second, this is an example, an example, an
    example of something that I need to achieve.
    Third, you are asking for a code, to me that
    sounds as if your asking for homework. Fourth,
    I did not ask for any rude comments. Fith, in
    the future please do not reply to my messages at ALL
    if you can not help!!!!
    Sixth, We did not ask for lazy goofs to post here.
    Seventh, In the future please do not post here. Take a hike - there's the virtual door.

  • Help with arrays & counting characters in arrays

    I am trying to figure out how to count how many times each characters appears in the array (but I have to do all the counts at once).
    I am supposed to store the counts in an int[] array of 27 elements (26 letters & an extra count for everything else). How would I go about declaring the array, allocating it, & then setting each of the 27 elements zero?
    Thanks so much the help.
    public class CharCount {
         public static void main(String[] args) {
              new CharCount().process();
         public void process() {
             // This declares an array of char and then assigns it a value.  The value comes from another one
             // of my secret programs.
             char[] countThese = Lab8.simple();
             printChars(countThese);
             for (int count =0; count < countThese.length; count++) {
              System.out.println(countThese[count]);
        // This method should print the characters in the array called print, one-by-one
        // Use a println ONLY after all the chars have been printed.
        public void printChars(char[] print) {
        public int charToInt(char ch) {
         if (ch >= 'A' && ch <= 'Z')
             return ch - 'A';
         else if (ch >= 'a' && ch <= 'z')
             return ch - 'a';
         else return 26;
    }

    I take it the charToInt method was given to you. If you don't know what it does, it will give you a value from 0 to 26 depending on what char you pass as a parameter. So if you pass an 'a' or an 'A' it will return 0, 25 for 'z' or 'Z' and 26 for anything else. You use this value to access an array an increment the value (the number of times that letter has occured.
    int value = charToInt('a');
    arr[value]++;
    System.out.println("Number of a's = " + arr[0]);

  • Htmldb_application array count 0 when it shouldn't be

    This was working until I made modifications to the application, i.e. tabs, menus and such. It uses a manually built tabular form - that part works and displays with correct values, but when I try to access the array with a loop it appears to be empty.
    I also have an item P3_WHERE_CLAUSE that runs a similar loop to build a where clause for validation. I modified it to debug as shown below.
    Any hints greatly appreciated - can't figure out how I broke it.
    Here's the query for the tabular form:
    select
    htmldb_item.select_list_from_query(
    1,key_id,
    'select key_id, object_key from
    val_object_key k,
    VAL_OBJECT o
    where o.object_name = :P3_OBJECT_NAME
    and k.object_id = o.object_id') Key_id,
    htmldb_item.select_list_from_query(2,object_key,
    'select object_key, object_key from
    val_object_key k,
    VAL_OBJECT o
    where o.object_name = :P3_OBJECT_NAME
    and k.object_id = o.object_id') Key,
    htmldb_item.text(3,'',50) Value
    from VAL_OBJECT_KEY k,
    VAL_OBJECT o
    where o.object_name = :P3_OBJECT_NAME
    and k.object_id = o.object_id;
    Here's the code to save the page information (several items in a cascading form and then it loops to include values from the tabular form). The loop does not execute.
    DECLARE P_KEY_ID NUMBER;
    kvs_id NUMBER;
    BEGIN
    select prov_id.nextval into kvs_id from dual;
    insert into key_val_set kvs_id values (kvs_id);
    for i in 1..htmldb_application.g_f01.count
    loop
    insert into key_value (KV_ID,KEY_ID,KEY_VALUE,KVS_ID)
    values
    prov_id.nextval,
    htmldb_application.g_f01(i),
    htmldb_application.g_f03(i),
    kvs_id)
    end loop;
    INSERT INTO PROV_INSTANCE
    CLASS_ID,
    SOURCE_ID,
    DATE_OCCURED,
    KVS_ID
    VALUES
    :P3_CLASS_NAME,
    :P3_SRC_NAME,
    :P3_DATE_OCCURED,
    kvs_id
    commit;
    END;
    Here's the test loop:
    begin
    :P3_WHERE_CLAUSE := 'begin test';
    for i in 1..htmldb_application.g_f01.count
    loop
    :P3_WHERE_CLAUSE := 'where '||i;
    end loop;
    return :P3_WHERE_CLAUSE;
    end;

    Never mind - it was a page flow misunderstanding.

  • AppleScript Class recognition and Array count

    I have an application "SolarMaxOsX" written in Obj C
    This app is scriptable
    I have a class named Ups and in Ups.m I have written  following methods:
    - (id)init {
        self = [super init];
        NSLog(@"Init Ups at %p", self);
        self.upsName = [NSString stringWithFormat:@"S2000"];
    //    upsPort = [NSNumber numberWithInteger:1];
        self.upsPort = 1;
        self.upsIpAddress= [NSString stringWithFormat:@"192.168.10.101"];
        self.upsDataListToDisplayInTable = [self fillUpsListDictionary];
        _uniqueID = [[NSUUID UUID] UUIDString];
        return self;
    /* For appleScript recognition */
    - (BOOL)application: (NSApplication *)  sender delegateHandlesKey:(NSString *)key   {
        if ([key isEqualToString: @"Ups"]) return YES;
        if ([key isEqualToString: @"upsDescriptionDict"]) return YES;
        if ([key isEqualToString: @"networkStatus"]) return YES;
        if ([key isEqualToString: @"networkOk"]) return YES;
        return NO;
    - (NSUniqueIDSpecifier *)objectSpecifier {
        NSScriptClassDescription *appDescription = (NSScriptClassDescription *)[NSApp classDescription];
        return [[NSUniqueIDSpecifier alloc] initWithContainerClassDescription:appDescription containerSpecifier:nil key:@"Ups" uniqueID:self.uniqueID];
    In AppDelegate.m:
    There is an array : Upss declared as follows:
    NSArray (Upss *) Ups; declared and initialised in AppDelegate.m file
    self.Upss = [self initUpss];
    sdef file for SolarMax Suite follows (compiles correctly)
    <suite name="SolarMax Suite" code="SMap" description="Apple Events supportés par l&apos;application SolarMaxMain">
    <class name="Ups" code="SCup" description="An object UPS in SolarMaxOsX." >
    <cocoa class="Ups" inherits="item" plural="Upss"/>
    <property name="id" code="ID  " type="text" access="r" description="The unique identifier of the note.">
    <cocoa key="uniqueID"/>
    </property>
    </class>
    <element description="List of Ups" type="Ups">
    <cocoa key="Upss"/>
    </element>
    <class name="AppDelegate" code="SCad" description="main class in SolarMaxOsX.">
    <cocoa class="AppDelegate" />
    // Liste des Ups reconnus dans le fichier de configuration
    <property name="Upss" code="SMno" type="Ups" access="r">
    <cocoa key="Upss"/>
    </property>
    </class>
    </suite>
    I want to get a count for array Upss
    Script follows
    tell application "/Users/guydesbief/Library/Developer/Xcode/DerivedData/SolarMaxOsX-cgcuhyptmpmtiegixfnbbhpexjhn/Build/Products/Debug/SolarMaxOsX.app" to activate
    -- delay 30
    tell application "/Users/guydesbief/Library/Developer/Xcode/DerivedData/SolarMaxOsX-cgcuhyptmpmtiegixfnbbhpexjhn/Build/Products/Debug/SolarMaxOsX.app"
        --    set nomAppli to the name of application
        --    set theWindows to windows
        set NbWin to the count of windows
        set theWindow to first item of windows
        properties of the theWindow
        tell window "UPS Sumary"
            --click on "Statistics button"
            -- click  on button 1 of theWindow
            --        set enabled of button1 to true
        end tell
        --class of Upss
        count of Upss
    end tell
    I get the following answers:
    tell application "SolarMaxOsX"
        activate
        count every window of current application
            --> 1
        get item 1 of every window
            --> window id 3113
        get properties of window id 3113
            --> {closeable:true, zoomed:false, class:window, index:1, visible:true, name:"UPS Sumary", miniaturizable:true, id:3113, miniaturized:false, resizable:true, bounds:{1485, 31, 1985, 579}, zoomable:true}
        count every Ups of current application
            --> error number -1728
    Résultat :
    error "Erreur dans SolarMaxOsX : Il est impossible d’obtenir every Ups." number -1728 from every Ups
    What do I have missed ?
    Logiciel  OS X 10.9.5 (13F34) (Mavericks)
    Xcode Version 6.1 (6A1052d)
    Éditeur AppleScript Version 2.6.1 (152.1)
    AppleScript 2.3.2

    Hi Hiroto
    It is much better thanks
    Now count of onduleurs works
    Hi Hiro,
    It is much better Thanks for your help
    Now, count od onduleurs works
    tell application "/Users/guydesbief/Library/Developer/Xcode/DerivedData/SolarMaxOsX-cgcuhyptmpmt iegixfnbbhpexjhn/Build/Products/Debug/SolarMaxOsX.app" to activate
    -- delay 30
    tell application "/Users/guydesbief/Library/Developer/Xcode/DerivedData/SolarMaxOsX-cgcuhyptmpmt iegixfnbbhpexjhn/Build/Products/Debug/SolarMaxOsX.app"
           --    set nomAppli to the name of application
           --    set theWindows to windows
           class of onduleurs
           count of onduleurs
           --    get properties
           set NbWin to the count of windows
           set theWindow to first item of windows
           properties of the theWindow
           tell window "UPS Sumary"
                 --click on "Statistics button"
                 -- click  on button 1 of theWindow
                 --           set enabled of button1 to true
           end tell
           get properties
           get id of first onduleur of onduleurs
    The results in appleScript:
    tell application "SolarMaxOsX"
             activate
             get class of every onduleur
                     --> {onduleur, onduleur, onduleur}
             count every onduleur of current application
                     --> 3
             count every window of current application
                     --> 1
             get item 1 of every window
                     --> window id 9796
             get properties of window id 9796
                     --> {closeable:true, zoomed:false, class:window, index:1, visible:true, name:"UPS Sumary", miniaturizable:true, id:9796, miniaturized:false, resizable:true, bounds:{30, 28, 530, 576}, zoomable:true}
             get properties
                     --> error number -10000
    Résultat :
    error "Erreur dans SolarMaxOsX : Le gestionnaire AppleEvent a échoué." number -10000
    And the results of my logging in Objective C debugger:
    My sdef file
    2014-12-01 23:56:36.040 SolarMaxOsX[37551:303] Appdelegate handles onduleursArray
    2014-12-01 23:56:36.040 SolarMaxOsX[37551:303] handles onduleursArray OK
    2014-12-01 23:56:36.041 SolarMaxOsX[37551:303] Appdelegate handles onduleursArray
    2014-12-01 23:56:36.041 SolarMaxOsX[37551:303] handles onduleursArray OK
    2014-12-01 23:56:36.042 SolarMaxOsX[37551:303] Appdelegate handles orderedWindows
    2014-12-01 23:56:36.042 SolarMaxOsX[37551:303] Appdelegate handles orderedWindows
    2014-12-01 23:56:36.043 SolarMaxOsX[37551:303] Appdelegate handles orderedWindows
    2014-12-01 23:56:36.043 SolarMaxOsX[37551:303] Appdelegate handles orderedWindows
    2014-12-01 23:56:36.044 SolarMaxOsX[37551:303] Appdelegate handles scriptingProperties
    2014-12-01 23:56:36.044 SolarMaxOsX[37551:303] Appdelegate handles classCode
    2014-12-01 23:56:36.044 SolarMaxOsX[37551:303] Appdelegate handles onduleursArray
    2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] handles onduleursArray OK
    2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] Appdelegate handles terminologyVersion
    2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] Appdelegate handles version
    2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] Appdelegate handles name
    2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] Appdelegate handles isActive
    2014-12-01 23:56:36.046 SolarMaxOsX[37551:303] An exception was thrown during execution of an NSScriptCommand...
    2014-12-01 23:56:36.046 SolarMaxOsX[37551:303] Error while returning the result of a script command: the result object...
    classCode = 1667330160;
    isActive = 1;
    name = SolarMaxOsX;
    onduleursArray =     (
    "<Ups: 0x6000002c0bd0>",
    "<Ups: 0x6100002c24c0>",
    "<Ups: 0x6000000df100>"
    terminologyVersion = 1;
    version = "1.1";
    ...could not be converted to an Apple event descriptor of type 'application properties'. The 'onduleursArray' entry could not be converted to an Apple event descriptor of type 'onduleur'. This instance of the class '__NSArrayM' returned nil when sent -objectSpecifier (is it not overridden?) and there is no coercible type declared for the scripting class 'onduleur'.
    It seems that my objectSpecifier method in Ups Category (or Ups class) is never called
    My sdef File:
        <!-- Suite Solar Max -->
        <suite name="SolarMax Suite" code="SMap" description="Apple Events supportés par SolarMaxOsX">
            <!-- suppress warning for missing "savable file format" type -->
            <enumeration name="savable file format" code = "savf" hidden="yes">
                <enumerator name= "dummy" code="VTdm"
                description="A dummy file format."/>
            </enumeration>
            <class name="application" code="capp" description="SolarMaxOsX’s top level scripting object." plural="applications" inherits="application">
                <cocoa class="NSApplication"/>
    <element type="onduleur" access="r">
                        <cocoa key="onduleursArray"/>
                </element>
                <property name="onduleurs" code="SMor" description="Array of onduleurs." access="r">
                    <type  type="onduleur" list="yes"/>
                <cocoa key="onduleursArray"/>
                </property>
                <property name="name" code="pnam" description="The name of the application." type="text" access="r"/>
                <property name="frontmost" code="pisf" description="Is this the frontmost (active) application?" type="boolean" access="r">
                    <cocoa key="isActive"/>
                </property>
                <property name="version" code="vers" description="The version of the application." type="text" access="r"/>
                <property name="terminology version" code="TEvn" type="integer" access="r">
                    <cocoa key="terminologyVersion"/>
                </property>
            </class>
    <class name="onduleur" code="SCup" description="An object onduleur in SolarMaxOsX." plural="onduleurs">
                <cocoa class="Ups" inherits="item" />
                <property name="id" code="ID  " type="text" access="r" description="The unique identifier of the onduleur">
                    <cocoa key="uniqueID"/>
                </property>
                <property name="OnduleurName" code="pnam" description="The onduleur name. ." type="text">
                    <cocoa key="name"/>
                </property>
           </class>
            // Class SolarMaxOsX to access to first window
            <class name="SolarMaxOsX" code="SMos" description="main window in SolarMaxOsX.">
            <cocoa class="SolarMaxOsX" />
    </class>
        </suite>
    Categories for all classes in he same file: AppDelegate+AppleScriptExtensions.m (category file)
    //  SolarMaxOsX+AppleScriptExtensions.m
    //  SolarMaxOsX
    //  Created by  Guy DESBIEF on 28/11/2014.
    #import "AppDelegate+AppleScriptExtensions.h"
    #import "Ups.h"
    @implementation NSObject (MNscriptability)
    - (void) returnError:(int)n string:(NSString*)s {
        NSScriptCommand* c = [NSScriptCommand currentCommand];
        [c setScriptErrorNumber:n];
        if (s)
            [c setScriptErrorString:s];
    @end
    @implementation AppDelegate (AppleScriptExtensions)
    #define APPLESCRIPT_TERMINOLOGY_VERSION 1
    #pragma mark ACCESSOR METHODS
    -(NSNumber *) terminologyVersion {
        return [NSNumber numberWithInt:APPLESCRIPT_TERMINOLOGY_VERSION];
    // For appleScript recognition
    -(NSUInteger) countOfOnduleursArray
        MyLog(@"countOfOnduleursArray");
        return [self.onduleursArray count];
    - (Ups *) objectInOnduleursArrayAtIndex : (int) index {
        MyLog(@"objectInOnduleursArrayAtIndex %index", index);
         Ups *upsItem = [self.onduleursArray objectAtIndex:index];
        if (upsItem != nil)
            return upsItem;
        } return nil;
    - (Ups *) valueInOnduleursArrayAtIndex:(unsigned int)i {
        MyLog(@"valueInOnduleursArrayAtIndex %i", i);
        if (![[NSScriptCommand currentCommand] isKindOfClass:[NSExistsCommand class]])
            if (i >= [onduleursArray count]) {
                [self returnError:errAENoSuchObject string:@"No such Ups."];
                return nil;
        MyLog(@"valueInOnduleursArrayAtIndex index OK: %i", i);
        return [onduleursArray objectAtIndex: i];
    - (BOOL)application: (NSApplication *)  sender delegateHandlesKey:(NSString *)key   {
         MyLog(@"Appdelegate handles %@",key);
        if ([key isEqualToString: @"terminologyVersion"]) return YES;
         if ([key isEqualToString: @"onduleursArray"]) {
           MyLog(@"handles %@ OK",key);
         return YES;
        return NO;
    @end
    @implementation Ups (AppleScriptExtensions)
    - (NSUniqueIDSpecifier *) objectSpecifier
        MyLog(@"objectSpecifier (UPS) OK");
        return [[NSUniqueIDSpecifier allocWithZone:[self  zone]]
                initWithContainerClassDescription: (NSScriptClassDescription *)[NSApp classDescription]
                containerSpecifier: nil
                key: @"onduleursArray"
                uniqueID: uniqueID];
    @end
    AppDelegate+AppleScriptExtensions.h (category file)
    // SolarMaxOsX+AppleScriptExtensions.h
    //  SolarMaxOsX
    //  Created by  Guy DESBIEF on 28/11/2014.
    #import <Foundation/Foundation.h>
    #import "AppDelegate.h"
    @class AppDelegate;
    @class Ups;
    @interface NSObject (MNscriptability)
    - (void) returnError:(int)n string:(NSString*)s;
    @end
    @interface AppDelegate  (AppleScriptExtensions)
    #ifdef NDEBUG
    #define MyLog(f, ...)
    #else
    #define MyLog(f, ...) NSLog(f, ## __VA_ARGS__)
    #endif
    - (BOOL)application: (NSApplication *)  sender delegateHandlesKey:(NSString *)key;
    - (NSUInteger) countOfOnduleursArray;

  • Arrays - counting occurence

    Hello everyone :)
    A practical at college is requiring me to create a program that simulates throwing 3 dice a total of 5000 times and for it to tally the number of times that all possible answers have occurred. For example, with 3 dice the lowest you can get is 3 (three 1's) and highest, 18 (three 6's). Roll the three dice, see which of the 16 different outcomes (3-18) you have, and add 1 to the total number of occurrences that outcome has produced. After 5000 throws, I will need to see which outcome happened most often. I've been told I must use an array for counting the occurrences and it's the array part which is confusing me.
    Implementing the 3 dice and a method that simulates them being thrown was easy but I just do not have a clue how to:
    1) get it to be done 5000 times and
    2) the outcomes be tallied
    Heres the code I have so far..
    import java.lang.Math;
    public class ThreeDice
        public static int throwDie()
                double x = Math.random();
                double x2 = Math.random();
                double x3 = Math.random();
                x = (x * 6.0) + 1.0;
                x2 = (x2 * 6.0) +1.0;
                x3 = (x3 * 6.0) +1.0;
                int dice1 = (int)Math.floor(x);
                int dice2 = (int)Math.floor(x2);
                int dice3 = (int)Math.floor(x3);
                return dice1 + dice2 + dice3;
        public static void main(String args[])
        }the throwDie method has to be used in main method but I'm stuck as for what to do next I'm afraid.

    Hello Looce and thank you for the welcome,
    Using my (very limited) knowledge I've managed to get the first part done (roll the 3 dice 5000 times) and for now I've just set it to print all 5000 results and alas it indeed prints 5000 results.
    The second part though I'm still stuck on, I was hoping google would be my savior but sadly not this time.
    I should have probably said in my first post that I'm a complete beginner for Java but with it being used both this year and next year for college, I hope to be fairly skilled in the use of it one day :)
    An update of the code:
    import java.lang.Math;
    public class ThreeDice
        public static int throwDie()
                double x = Math.random();
                double x2 = Math.random();
                double x3 = Math.random();
                x = (x * 6.0) + 1.0;
                x2 = (x2 * 6.0) +1.0;
                x3 = (x3 * 6.0) +1.0;
                int dice1 = (int)Math.floor(x);
                int dice2 = (int)Math.floor(x2);
                int dice3 = (int)Math.floor(x3);
                return dice1 + dice2 + dice3;
        public static void main(String args[])
                for(int i=0; i<5000; i++){
                    System.out.println(throwDie());
        }

  • Ideas on transforming a byte array?

    I'm writing a program to compress files - I read it in, transform it and then write it out again. I'm just having a little confusion with the transforming.
    I'm keeping it as basic as possible and just starting with finding and replacing repeating bytes with an instruction of how many times the following byte is repeated. ie a a a a a = 5 a _ _ _
    In order to do this I create a temporary array to write to (initialised to the same size as the input) and then check through for repetitions. If something is repeated more than twice (3+), then a marker byte is put in (I wanted to have specific ones for however many times the byte is repeated - within reason - which is the switch statement below), the next byte is the byte to be repeated and then I want to jump forward to the next different byte.
    I then go through the temp array count the repetitions, create a new smaller byte array and write temp[] to output[] ignoring the bytes that are repeated.
    This is what I have so far, but it doesn't quite do what I want:
    public class Transformer {
         byte[] input;
         byte[] temp;
         byte[] output;
         byte rep;
         public Transformer() {
         public byte[] transform(byte[] in) {
              input = in;
              temp = new byte[in.length];
              output = new byte[count(input, temp)];
              output = compress(temp, output);
              return output;
         private int count(byte[] from, byte[] to) {
              int k = 0; // total bytes copied so far
              byte markerByte = (byte) 0xE1;
              for (int i = 0, j = 0; i < from.length; i = j) {
                   for (j = i+1; j < from.length && from[j] == from[i] && j-i < 128; j++);
                   if (j-i >= 3) {
                        to[k++] = markerByte;
                        to[k++] = (byte) (j-i);
                        to[k++] = from[j-1];
                   } else {
                        to[k] = from[k];
                        k = i+1;
              return k;
            // (the following method isn't finished)
         private byte[] compress(byte[] from, byte[] to) {
              for (int i = 0; i < from.length; i++) {
                   if (from[i] == (byte) 0xE1) {
                        System.out.println("repeat");
                   System.out.println(from);
              return to;
         private byte getRepeatByte(int numberOfRepeats) {
              byte instruction;
              switch (numberOfRepeats) {
              case 1: instruction = (byte) 0xE1; break;
              case 2: instruction = (byte) 0xE2; break;
              case 3: instruction = (byte) 0xE3; break;
              case 4: instruction = (byte) 0xE4; break;
              case 5: instruction = (byte) 0xE5; break;
              case 6: instruction = (byte) 0xE6; break;
              case 7: instruction = (byte) 0xE7; break;
              case 8: instruction = (byte) 0xE8; break;
              case 9: instruction = (byte) 0xE9; break;
              case 10: instruction = (byte) 0xEA; break;
              case 11: instruction = (byte) 0xEB; break;
              case 12: instruction = (byte) 0xEC; break;
              case 13: instruction = (byte) 0xED; break;
              case 14: instruction = (byte) 0xEE; break;
              case 15: instruction = (byte) 0xEF; break;
              default: instruction = (byte) 0xE0; break;
              return instruction;
    At the moment I'm using a marker byte in the transform() but I want to be using the switch statement to work out the right byte to put in first.
    Does anyone have any advice on if I'm doing this in a ridiculous way or if my methods won't work.. As I haven't written a decompressor yet, it's pretty hard to test!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    baftos - thank you for your advice, i will try that and see how it goes.
    Jos - it is your method and thank you very much for it! It's part of an ongoing project of mine, which is turning out to be more challenging than i originally thought - when i posted on the other forum your loop did perfectly what I was trying to do at the time. I need all the advice i can get and hence post on multiple forums.

  • Arrays.equals doesnt seem to be working

    Hi
    i have an app that copys the contents of an object array into another, then reruns and compares its contents to the previous copy. they should be equal, but i get a not equal message. i have tried printing out the objects in a loop to see whats happening, i get this:
    (code)
    for(int i = 0; i < count; i++)
    System.out.println(TestPcContainer);
    System.out.println(TestPcContainerCopy[i];
    output:
    Thread[Thread-20,5,main] (orig element 0)
    Thread[Thread-15,5,main] (copy element 0)
    Thread[Thread-21,5,main] (orig element 1
    Thread[Thread-16,5,main] (copy element 1)
    Thread[Thread-22,5,main] (orig element 2)
    Thread[Thread-17,5,main] (copy element 2)
    i dont understand why i keep getting its not equal. i have copied the arrays using : System.arraycopy(TestPcContainer, 0, TestPcContainerCopy, 0, count);
    and i compare by doing: if(Arrays.equals(TestPcContainer, TestPcContainerCopy)) { System.out.println("equal");}else not ......
    thanx for any help on this
    ness

    ok,heres the code:
    ckage tmhealthproject;
    import com.xyratex.utils.EventHandler;
    import com.xyratex.utils.EventInterface;
    import com.xyratex.xyrmi.io.XYRMIMessageHandler;
    import com.xyratex.xyrmi.io.XYRMIObjectInterface;
    import com.xyratex.xyrmi.tcp.XYRMIClient;
    import java.io.*;
    import java.net.UnknownHostException;
    import jicmp.*;
    import java.util.*;
    * <p>Title: TMHealthStatusTestPc </p>
    * <p>Description: Class reads in ip addresses from IpAddress.txt, then creates 16 new
    * TMHealthStatusTestPc objects, allocating each one an ip address from the txt file. Each object represents
    * a tm, and holds 3 fields of data: ipaddress, Morb and TM. These attributes are set to 1 or a zero depending
    * on whether the tm is on or offline, its orb is running and the TestManager software is running. Once these
    * checks have been done, the data is sent to the calling application, either terminal or applet.
    * <p>Copyright: Copyright (c) 2003</p>
    * <p>Company: Xyratex</p>
    * @author Vanessa Radford
    * @version 1.0
    public class TestPc extends Thread implements XYRMIMessageHandler, EventInterface
    FileReader filereader;
    BufferedReader bufferedreader;
    String ipaddress = new String();
    int count;
    TestPc TestPcContainer[];
    TestPc TestPcContainerCopy[];
    TestPc testpc = null;
    int ipvalid = 0;
    int morbvalid = 0;
    int tmvalid = 0;
    int result = 0;
    String tmname = new String();
    String host = "127.0.0.1";
    String className = "className";
    String objectName = "broadCast";
    int port = 9765;
    String object = new String("Object:");
    XYRMIClient Orblink;
    XYRMIClient Orblink1[];
    XYRMIClient Orblink2[];
    String initalMessage1 = (objectName + " " + className + "1 ");
    String initalMessage2 = (objectName + " " + className + "2 ");
    String initialMessage3 = (objectName + " " + className + "3 ");
    EventHandler StatusRequestTimer = null;
    EventHandler StatusResponseTimer = null;
    int counter = 0;
    String viewMessage = (objectName + " StatusView " + "status " + "numberoftms:");
    *</p> This method opens the TMipaddress.txt file, reads in each line, creates a
    * TMHealthStatusTestPc object for each line that is read in, and assign it an ip address.
    * These objects are then stored into a container called TestPcContainer</p>
    public void initializeObjects()
    counter ++;
    //set a count variable to zero. this variable sets the sizes of the Container and Orblink arrays
    count = 0;
    //try to find the file TMipaddress.txt
    try
    filereader = new FileReader("TMipaddress.txt");
    bufferedreader = new BufferedReader(filereader);
    //count how many ip addresses it holds
    while ((ipaddress = bufferedreader.readLine()) != null)
    count ++;
    catch(IOException ioexception)
    System.out.println(ioexception.getMessage());
    //open the file again and read each line
    //now we have the number of tms in the txt file, call the setArraySizes method
    //and send it the count variable. This will inialize the containers and arrays to the correct size
    setArraySizes(count);
    TestPcContainer = new TestPc[count];
    try
    filereader = new FileReader("TMipaddress.txt");
    bufferedreader = new BufferedReader(filereader);
    for(int i = 0; i < count; i++)
    //for each ip address create a new testpc object
    testpc = new TestPc();
    //read in each line from the txt file
    ipaddress = bufferedreader.readLine();
    //create a tokenizer object for each line, and ignore any tabs, spaces or newlines
    StringTokenizer str = new StringTokenizer(ipaddress, " \n\t\r,");
    //send to the setTmName method the first part of the line which holds the tm name
    testpc.setTmName(str.nextToken());
    //send to toe setIp method the second part of the line whcih holds the ip address
    testpc.setIp(str.nextToken());
    //add the object to the container
    TestPcContainer[i] = testpc;
    catch(IOException e)
    //call the method that checks the ip addresses
    checkIp();
    *<p>This method creates a new ICMPPing object in a loop, and passes in a TestPc object
    * as an argument to its constructor. The ICMPPing object extracts the TestPcs host ip
    * address and conducts an ICMP ping on it. The result of this is passed back into setIPValid.
    * The loop ends when all of the TestPc objects stored in the container have been passed in.
    * There is then a 10 second sleep for the data to be collected, then the morb is done </p>
    *@param pc Takes a TMHealthStatusTestPc object as its argument
    public void checkIp()
    for(int i = 0; i < count; i++)
    //create a new ICMPPing object and pass in each object in the container
    ICMPPing checkIPAddress = new ICMPPing(TestPcContainer);
    try
    //sleep so that the data can be collected
    Thread.sleep(2000);
    catch(Exception e)
    System.out.println("message in checkip is " + e.getMessage());
    //call the morb check
    System.out.println("checking morbavail");
    checkMorbAvail();
    public int doSomething()
    if(counter != 1)
    if(Arrays.equals(TestPcContainer, TestPcContainerCopy))
    StatusRequestTimer();
    else
    sendRMI();
    StatusRequestTimer();
    if(counter ==1)
    sendRMI();
    StatusRequestTimer();
    return 1;
    public void setArraySizes(int count)
    TestPcContainer = null;
    if(TestPcContainerCopy == null)
    TestPcContainerCopy = new TestPc[count];
    if(Orblink1== null)
    Orblink1 = new XYRMIClient[count];
    if(Orblink2 == null)
    Orblink2 = new XYRMIClient[count];
    *<p>Method to send RMI message to StatusView applet. Checks to see if an OrbLink has already been created,
    * if so uses XYRMIMessageHandler to forward message. Otherwise registers with the Orb of the TM and forwards
    * message within registration</p>
    *@return int
    public int sendRMI()
    StringBuffer ipbuffer = new StringBuffer();
    for (int t = 0; t < count; t++)
    t++;
    ipbuffer.append(" Object" + t + ":");
    t--;
    ipbuffer.append("\"" + TestPcContainer[t].getTmName() + ",");
    if(TestPcContainer[t].ipvalid == 1)
    if(TestPcContainer[t].morbvalid == 1)
    if(TestPcContainer[t].tmvalid == 1)
    ipbuffer.append("OK\"");
    else
    ipbuffer.append("NoTestMan\"");
    else
    ipbuffer.append("NoOrb\"");
    else
    ipbuffer.append("TimedOut\"");
    String result = ipbuffer.toString();
    try
    if(counter != 1)
    Orblink.XYRMIMessageHandler(viewMessage + "\"" + count + "\"" + result);
    else
    Orblink = new XYRMIClient(this, host, port, viewMessage + "\"" + count + "\"" + result);
    Orblink.SetIdentity(className, objectName);
    Orblink.start();
    catch(Exception e)
    System.out.println("error in sendrmi " + e.getMessage());
    return 1;
    *<p>This method runs the applicatoin every 60 seconds, so that accurate data is recorded</p>
    public void StatusRequestTimer()
    StatusRequestTimer = new EventHandler(this, "message");
    StatusRequestTimer.initialise();
    StatusRequestTimer.startEvent(90);
    public void eventMessage(Object obj, String s)
    if(obj == StatusRequestTimer)
    System.arraycopy(TestPcContainer, 0, TestPcContainerCopy, 0, count);
    TestPcContainer = null;
    testpc = null;
    initializeObjects();
    *<p>method to set an ip address </p>
    *@param ipadd IP address
    public void setIp(String ipadd)
    ipaddress = ipadd;
    public void setTmName(String tm)
    tmname = tm;
    *<p>method to get an ip address</p>
    *@return string ip address
    public String getIp()
    return ipaddress;
    public String getTmName()
    return tmname;
    *<p>method to get whether the tm was valid, meaning it responded or not. /p>
    *@return string ip address
    public int getTmValid()
    return tmvalid;
    *<p>method to get whether the ip address was valid, meaning online or not, 1 for valid, 0 for not</p>
    *@return string ip address
    public int getIpValid()
    return ipvalid;
    *<p>method to get whether the morb on the TestPc is running or not, 1 for valid, 0 for invalid</p>
    *@return int morbValid
    public int getMorbValid()
    return morbvalid;
    *<p>method to set validity of the ip addres, recieves result from TMHealthStatusICMPcheck</p>
    *@param result passed in result of validity check on ip address, 1 for valid, 0 for invalid</p>
    public void setIPValid(int result)
    ipvalid = result;
    *<p>method to set validity of the Morb to the result</p>
    *@param result passed in result of validity check on morb, 1 for valid, 0 for invalid</p>
    public void setMorbValid(int result)
    morbvalid = result;
    *<p>method to set validity of the Morb to the result</p>
    *@param result passed in result of validity check on morb, 1 for valid, 0 for invalid</p>
    public void setTmValid(int result)
    tmvalid = result;
    *<p>method to create new XYRMIClient object, pass to it a TMHealthStatusTestPc object, extract
    * its ip address, then send an rmi message to the orb of that machine. Used to check if the TestPc's
    * Orb is runnning.
    *@param pc TMHealthStatusTestPc object
    public int checkMorbAvail()
    for(int q = 0; q < count; q++)
    if(TestPcContainer[q].getIpValid() == 1)
    host = TestPcContainer[q].getIp();
    if(counter != 1)
    Orblink1[q].XYRMIMessageHandler(initalMessage2 + host);
    }//close if
    else
    try
    Orblink1[q] = new XYRMIClient(this, host, port, initalMessage2 + host);
    Orblink1[q].SetIdentity(className + "2", objectName);
    Orblink1[q].start();
    } //close try
    catch(Exception e)
    System.out.println("error in checkmorbavail" + e.getMessage());
    }//close catch
    }//close if
    try
    Thread.sleep(30000);
    catch(Exception e)
    System.out.println("errror here");
    checkTmAvail();
    return 1;
    *<p>method to register with the Orb and send a message to its TestManager. If successful sends
    * initial message consisting of the ip address of the TestPc plus "tm" attached to the end.
    * Used to check whether the TestManager software is running on that machine</p>
    *@param pc takes a TMHealthStatusTestPc object as argument
    public int checkTmAvail()
    for(int r = 0; r < count; r++)
    if(TestPcContainer[r].getMorbValid() == 1)
    host = TestPcContainer[r].getIp();
    if(counter != 1)
    Orblink2[r].XYRMIMessageHandler(initialMessage3 + host + "tm");
    else
    try
    Orblink2[r] = new XYRMIClient(this, host, port, initialMessage3 + host + "tm");
    Orblink2[r].SetIdentity(className + "3", objectName);
    Orblink2[r].start();
    catch(Exception e)
    System.out.println("error in checktm is " + e.getMessage());
    else
    System.out.println("not valid");
    try
    Thread.sleep(1000);
    catch(Exception e)
    doSomething();
    StatusRequestTimer();
    return 1;
    *<p>method to create a new XYRMIObjectInterface to handle incoming messages. Checks to see
    *whether the incoming meesage has the method name of the ipaddress of each tm meaning that its morb
    *has been successfully registered with. Also checks to see if the method has the method name of
    *the ipaddress of the tm plus "tm" attached to the end, meaing that the tm has successfully received
    *the message and is returning with conformation. </p>
    *@return int
    *@param s Takes as a parameter a string
    public synchronized int XYRMIMessageHandler(String s)
    XYRMIObjectInterface msg = null;
    XYRMIObjectInterface msg1 = null;
    msg1 = new XYRMIObjectInterface(s);
    if(msg1.IsMethodName("RequestTestManagerStatus"))
    System.out.println("got requesttestmanstatus, sending rmi");
    sendRMI();
    else
    for (int i = 0; i < count; i ++)
    msg = new XYRMIObjectInterface(s);
    try
    if(msg.IsMethodName(TestPcContainer[i].getIp()))
    TestPcContainer[i].setMorbValid(1);
    System.out.println("setting morb valid");
    if(msg.IsMethodName(TestPcContainer[i].getIp() + "tm"))
    TestPcContainer[i].setTmValid(1);
    System.out.println("setting tmvalid");
    catch(Exception e)
    System.out.println("message in xyrmimesagehandler is " + e.getMessage());
    return 1;

  • Error with declaring a method with array variable

    Hi,
    I had implemented this:
    import java.awt.*;
    import javax.swing.*;
    public class Oefening1
         public static void main(String args[])
              int array[]= new int[10];
              int getal;
              JTextArea outputArea = new JTextArea();
              Container container = getContentPane();
              container.add(outputArea);
              public void invoerRij(int array[10])
                   output +=" ";
                   for(int counter = 0; counter <10;counter++){
                        output +="Geef een getal in"+"\n"+array[counter]+"\n";
                        outputArea.setText(output);
    I had comilated this code while the compiler gave errors like these:
    A:\Oefening1.java:15: illegal start of expression
              public void invoerRij(int array[10])
    ^
    A:\Oefening1.java:24: ';' expected
    ^
    A:\Oefening1.java:12: cannot resolve symbol
    symbol : method getContentPane ()
    location: class Oefening1
              Container container = getContentPane();
    ^
    3 errors
    Tool completed with exit code 1
    Now i have read my book and finded out that the declaration of a method always starts with public.
    Can anyone halp me solving these probs? Thanks
    Crazydj1

    The problem is that you didn't close the previous method definition.
    Compiler error messages (in any language) often mistakenly report false errors on perfectly valid code immediately following the actual error.
    When you post code on these forums, please wrap in in &#91;code]&#91;/code] tags.

  • Array problem - Related Selects

    Good Morning,
    I'm a newbie when it comes to this so I apologize ahead of time.
    I'm trying to build a Year/Make/Model related select search. I found a HTML, PHP, and the JQuery Related Select Plugin that i'm trying to convert to use with CF.
    It looks like i can use an array to replace the PHP page that supplies static data:
    <?php
    $stateID = $_GET['stateID'];
    $countyID = $_GET['countyID'];
    $townID = $_GET['townID'];
    $html = $_GET['html'];
    $states = array();
    $states['MA'] = "Massachusetts";
    $states['VT'] = "Vermont";
    $states['SC'] = "South Carolina";
    $counties = array();
    $counties['MA']['BARN'] = 'Barnstable';
    $counties['MA']['PLYM'] = 'Plymouth';
    $counties['VT']['CHIT'] = 'Chittenden';
    $counties['SC']['ANDE'] = 'Anderson';
    if($stateID && !$countyID && !$townID){
              echo json_encode( $counties[$stateID] );
    } elseif( $stateID && $countyID && !$townID ) {
              echo json_encode( $towns[$stateID][$countyID] );
    } elseif( isset($villages[$stateID][$countyID][$townID]) ) {
              echo json_encode( $villages[$stateID][$countyID][$townID] );
    } else {
              echo '{}';
    ?>
    I'm tryiing to convert the following into an array so that i can access it from the index.cfm page:
    <cfquery name="qYear" datasource="MyDS" username="MyUser" password="MyPass">
        select distinct YearRange
        from ExactFit2012
        order by YearRange
    </cfquery>
    <cfquery name="qMake" datasource="MyDS" username="MyUser" password="MyPass">
        select distinct Make
        from ExactFit2012
        order by Make
    </cfquery>
    <cfquery name="qModel" datasource="MyDS" username="MyUser" password="MyPass">
        select distinct Model
        from ExactFit2012
        order by Model
    </cfquery>
    <cfset myYear = ListToArray(ValueList(qYear.YearRange)) />
    <cfset myMake = ListToArray(ValueList(qMake.Make)) />
    <cfset myModel = ListToArray(ValueList(qModel.Model)) />
    <Cfoutput>
    #myYear#<br>
    #myMake#<br>
    #myModel#
    </Cfoutput>
    When i do this i get the error:
    Error Occurred While Processing Request
    Error Executing Database Query.
    [Macromedia][SQLServer JDBC Driver][SQLServer]Invalid column name 'Ford'.
    index.cfm:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>jQuery Related Selects</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
    <script src="src/jquery.relatedselects.min.js" type="text/javascript"></script>
    <style type="text/css">
    body { font:12px helvetica, arial, sans-serif; }
    </style>
    <script type="text/javascript">
    $(function(){
              $("#example-1, #example-3").relatedSelects({
                        onChangeLoad: 'MyArray.cfm',
                        defaultOptionText: 'Choose an Option',
                        selects: {
                                  'Make':                    { loadingMessage:'Loading Year...' },
                                  'YearRange':                    { loadingMessage:'Loading Make...' },
                                  'Model':                    { loadingMessage:'Loading Model...' },
                                  'OverallSize':          {}
    </script>
    </head>
    <body>
    <form id="ymm">
              <select name="YearID">
              <option value="">Choose Year &raquo;</option>
              <cfoutput query="qYear">
              <option value="#YearRange#">#YearRange#</option>
        </cfoutput>
              </select>
              <select name="Make">
              <option value="">Choose Make &raquo;</option>
              </select>
              <select name="Model">
              <option value="Model">Choose Model &raquo;</option>
              </select>
              <select name="OverallSize">
              <option value="">Choose Size &raquo;</option>
              </select>
    </form>
    </body>
    </html>
    I may be going avout this all woring, but i have tried 3 cfc tutorials with no luck so i'm hoping the JQuery Related Select will do the trick.
    Cheers,
    Aaron

    good

  • Array Trouble

    So I am new to Java, and took my first semester of a java course. It was hard for me at first, but I am slowly improving. My professor posted this as our last assignment for the semester, and I am having trouble with it as it involves arrays. I do not really know where to start, and any help would be greatly appreciated. I will post the assignment below, followed by the small bit of code I have so far. By no means do I want the answers to this, as I actually do enjoy learning, but any type of help, input, suggestions, etc are greatly appreciated. Thanks in advance!
    Write a program which prompts the user to input a series of characters, one at a time. The program will stop prompting the user for characters once the user enters an exclamation point ('!').
    Using an array, count the number of occurrences of each letter (regardless of whether it is upper or lower case (so for example, an 'A' and an 'a' both count for the first letter of the alphabet). In a separate counter, also count the total number of "other" characters ('.', '?', ' ', '2', etc.). The final exclamation point does not count.
    Print out the count for each letter found (but not for those which where not found!)
    Print the count of the non-letter characters.
    List the characters that were not found (e.g. "The following letters were not found: t, z, c.").
    By inspecting the array, print out the total number of all of the vowels, and the total number of all of the consonants.
    Finally, print out which letter was found the most times. (Note there may be more than one letter which has the maximum count attached to it.) Also, print out which letter (or letters) was found the least number of times, but make certain to exclude letters which were not found at all.
    This is the small amount of code I have thus far.
    import javax.swing.JOptionPane;
    public class asgn6 {
       public static void main( String[] args )
          int character;
           String letter = JOptionPane.showInputDialog("Please enter a letter (Type ! when finished) ");
           character = Integer.parseInt (letter);
         if(letter.equals("!"))
         System.exit(0);
    }

    derajfast wrote:
    char letter;
    do {
    String input = JOptionPane.showInputDialog("Please enter a letter (Type ! when finished) ");
    letter= input.charAt(0);
    }while (letter != '!');So I figured out the loop!Exellent, that's exactly right.
    Now I need a lot of assistance for the arrays part, as that is what I understand least with this assignment.The easiest way I see it is to make an array of ints 128 elements long. Each element is the counter for the character that indexes it.
    For instance, 'A' is ASCII 65. So array[65] is the counter for how many times 'A' has been seen. You can use chars like you would use ints, so you can do this: array['A'] and it will convert it to it's ASCII value. Each time you read an input char, increment array[letter].
    Then when you're done with input, you can print out each one like this
    for each element i in the array
       print out (char)i followed by array                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Modify hard coded array to database pull

    Hello all,
    I'm new to the array stuff, and am having problems finding a tutorial or instructions on how to modify a hard coded array to something pulled from a database.  I can only find tutorials on how to do it hardcoded.  They keep saying it is possible, but never say how to do it.  The original tutorial that I'm trying to learn which brought up this question can be found at:  http://www.brandspankingnew.net/archive/2007/02/ajax_auto_suggest_v2.html
    So as an example, if I've got the database connection already established as:
       $con = mysql_connect("localhost", "root", "") or die('Could not connect to server');
       mysql_select_db("my_database", $con) or die('Could not connect to database');
    With fields as my_database_names, my_database_ratings, and my_database_images; how do I modify the below code to use the database information instead of using the hardcoded array?  Any suggestions (or letting me know of where a good tutorial is) would be appreciated.
    <?php
    note:
    this is just a static test version using a hard-coded countries array.
    normally you would be populating the array out of a database
    the returned xml has the following structure
    <results>
    <rs>foo</rs>
    <rs>bar</rs>
    </results>
    $aUsers = array(
      "Adams, Egbert",
      "Altman, Alisha",
      "Archibald, Janna",
      "Auman, Cody",
      "Bagley, Sheree",
      "Ballou, Wilmot",
      "Bard, Cassian",
      "Bash, Latanya",
      "Beail, May",
      "Black, Lux",
      "Bloise, India",
      "Blyant, Nora",
      "Bollinger, Carter",
      "Burns, Jaycob",
      "Carden, Preston",
      "Carter, Merrilyn",
      "Christner, Addie",
      "Churchill, Mirabelle",
      "Conkle, Erin",
      "Countryman, Abner",
      "Courtney, Edgar",
      "Cowher, Antony",
      "Craig, Charlie",
      "Cram, Zacharias",
      "Cressman, Ted",
      "Crissman, Annie",
      "Davis, Palmer",
      "Downing, Casimir",
      "Earl, Missie",
      "Eckert, Janele",
      "Eisenman, Briar",
      "Fitzgerald, Love",
      "Fleming, Sidney",
      "Fuchs, Bridger",
      "Fulton, Rosalynne",
      "Fye, Webster",
      "Geyer, Rylan",
      "Greene, Charis",
      "Greif, Jem",
      "Guest, Sarahjeanne",
      "Harper, Phyllida",
      "Hildyard, Erskine",
      "Hoenshell, Eulalia",
      "Isaman, Lalo",
      "James, Diamond",
      "Jenkins, Merrill",
      "Jube, Bennett",
      "Kava, Marianne",
      "Kern, Linda",
      "Klockman, Jenifer",
      "Lacon, Quincy",
      "Laurenzi, Leland",
      "Leichter, Jeane",
      "Leslie, Kerrie",
      "Lester, Noah",
      "Llora, Roxana",
      "Lombardi, Polly",
      "Lowstetter, Louisa",
      "Mays, Emery",
      "Mccullough, Bernadine",
      "Mckinnon, Kristie",
      "Meyers, Hector",
      "Monahan, Penelope",
      "Mull, Kaelea",
      "Newbiggin, Osmond",
      "Nickolson, Alfreda",
      "Pawle, Jacki",
      "Paynter, Nerissa",
      "Pinney, Wilkie",
      "Pratt, Ricky",
      "Putnam, Stephanie",
      "Ream, Terrence",
      "Rumbaugh, Noelle",
      "Ryals, Titania",
      "Saylor, Lenora",
      "Schofield, Denice",
      "Schuck, John",
      "Scott, Clover",
      "Smith, Estella",
      "Smothers, Matthew",
      "Stainforth, Maurene",
      "Stephenson, Phillipa",
      "Stewart, Hyram",
      "Stough, Gussie",
      "Strickland, Temple",
      "Sullivan, Gertie",
      "Swink, Stefanie",
      "Tavoularis, Terance",
      "Taylor, Kizzy",
      "Thigpen, Alwyn",
      "Treeby, Jim",
      "Trevithick, Jayme",
      "Waldron, Ashley",
      "Wheeler, Bysshe",
      "Whishaw, Dodie",
      "Whitehead, Jericho",
      "Wilks, Debby",
      "Wire, Tallulah",
      "Woodworth, Alexandria",
      "Zaun, Jillie"
    $aInfo = array(
      "Bedfordshire",
      "Buckinghamshire",
      "Cambridgeshire",
      "Cheshire",
      "Cornwall",
      "Cumbria",
      "Derbyshire",
      "Devon",
      "Dorset",
      "Durham",
      "East Sussex",
      "Essex",
      "Gloucestershire",
      "Hampshire",
      "Hertfordshire",
      "Kent",
      "Lancashire",
      "Leicestershire",
      "Lincolnshire",
      "Norfolk",
      "Northamptonshire",
      "Northumberland",
      "North Yorkshire",
      "Nottinghamshire",
      "Oxfordshire",
      "Shropshire",
      "Somerset",
      "Staffordshire",
      "Suffolk",
      "Surrey",
      "Warwickshire",
      "West Sussex",
      "Wiltshire",
      "Worcestershire",
      "Durham",
      "East Sussex",
      "Essex",
      "Gloucestershire",
      "Hampshire",
      "Hertfordshire",
      "Kent",
      "Lancashire",
      "Leicestershire",
      "Lincolnshire",
      "Norfolk",
      "Northamptonshire",
      "Northumberland",
      "North Yorkshire",
      "Nottinghamshire",
      "Oxfordshire",
      "Shropshire",
      "Somerset",
      "Staffordshire",
      "Suffolk",
      "Surrey",
      "Warwickshire",
      "West Sussex",
      "Wiltshire",
      "Worcestershire",
      "Durham",
      "East Sussex",
      "Essex",
      "Gloucestershire",
      "Hampshire",
      "Hertfordshire",
      "Kent",
      "Lancashire",
      "Leicestershire",
      "Lincolnshire",
      "Norfolk",
      "Northamptonshire",
      "Northumberland",
      "North Yorkshire",
      "Nottinghamshire",
      "Oxfordshire",
      "Shropshire",
      "Somerset",
      "Staffordshire",
      "Suffolk",
      "Surrey",
      "Warwickshire",
      "West Sussex",
      "Wiltshire",
      "Worcestershire",
      "Durham",
      "East Sussex",
      "Essex",
      "Gloucestershire",
      "Hampshire",
      "Hertfordshire",
      "Kent",
      "Lancashire",
      "Leicestershire",
      "Lincolnshire",
      "Norfolk",
      "Northamptonshire",
      "Northumberland",
      "North Yorkshire",
      "Nottinghamshire"
    $input = strtolower( $_GET['input'] );
    $len = strlen($input);
    $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 0;
    $aResults = array();
    $count = 0;
    if ($len)
      for ($i=0;$i<count($aUsers);$i++)
       // had to use utf_decode, here
       // not necessary if the results are coming from mysql
       if (strtolower(substr(utf8_decode($aUsers[$i]),0,$len)) == $input)
        $count++;
        $aResults[] = array( "id"=>($i+1) ,"value"=>htmlspecialchars($aUsers[$i]), "info"=>htmlspecialchars($aInfo[$i]) );
       if ($limit && $count==$limit)
        break;
    if (isset($_REQUEST['json']))
      header("Content-Type: application/json");
      echo "{\"results\": [";
      $arr = array();
      for ($i=0;$i<count($aResults);$i++)
       $arr[] = "{\"id\": \"".$aResults[$i]['id']."\", \"value\": \"".$aResults[$i]['value']."\", \"info\": \"\"}";
      echo implode(", ", $arr);
      echo "]}";
    else
      header("Content-Type: text/xml");
      echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?><results>";
      for ($i=0;$i<count($aResults);$i++)
       echo "<rs id=\"".$aResults[$i]['id']."\" info=\"".$aResults[$i]['info']."\">".$aResults[$i]['value']."</rs>";
      echo "</results>";
    ?>

    Thank you so much.  I was planning on hand coding it because my objective is to learn, not to have dreamweaver do it for me, so I will check out the link :
    http://docs.php.net/manual/en/mysqli.query.php.
    LOL, I thought I was just starting to understand MySQL, and now I've got to start learning MySQLi.  I hope there is not too much different between the two.  Thanks again.

  • Trying to 'simulate' an array of strings

    In pseudo-code what I would like to do is this:
    Array[x][3]
    Array[1][1] = "First"
    Array[1][2] = "Data1"
    Array[1][3] = true
    Array[2][1] = "Second"
    Array[2][2] = "Data2"
    Array[2][3] = false
    counter = 1
    while(counter < 3) {
    print Array[counter][1]
    counter++
    In Java-think I created a class of data, and wanted to create a series of elements (array) of this class. But, suprise, my code snippit below doesn't work....
    class DataSaved {
    String InputName;
    String InputValue;
    boolean IsHidden;
    public class test {
    public static void main(String [] args) {
    DataSaved dataum;
    int counter = 0;
    dataum = (DataSaved) DataSaved.firstElement();
    dataum.addElement("first","1data",true);
    dataum.addElement("second","2data",true);
    dataum.addElement("third","3data",true);
    dataum.addElement("xxxfirst","4data",true);
    dataum.addElement("fxxirst","5data",true);
    dataum.addElement("sixfirst","6data",true);
    dataum.addElement("7first","7data",true);
    dataum.addElement("8first","8data",true);
    dataum.addElement("9first","9data",true);
    // move to the top element
    datum.firstElement();
    while (counter < 6 ){
    System.out.println(dataum.nextElement());
    counter++;
    So....what am I not understanding, and how can I make this snippit work?

    Great, now your DataSaved class is correct.
    The next step is how to deal with arrays.
    Suppose you have an array of Strings. Here's how it looks like:
    String[] myArray;Before you can use it, you have to actually occupy the space it needs. (Arrays are objects in Java, so basically, but sloppily speaking, you have to instantiate an "array class"):
    myArray = new String[15];The length of the arrays in Java is constant. You have to tell the length during construction time, and you won't be able to change it later.
    Also, if you create an array as above, each of the elements will contain null (were it an array of primitive types, it would contain the appropriate version of zero for that primitive type). Therefore, you have to load the elements one by one:
    myArray[0] = new String("first string");
    myArray[1] = new String("second string");
    myArray[14] = new String("last string");As you see, indexing starts with zero. I also have to note, that "new String(...)" is an unnecessary and in most cases poor programming technic, the string constants would do in this case (but not if the array is not an array of strings but array of some kind of objects).
    Another note. It's usually a bad programming technic to reach the fields of another class. Sometimes we do, but only when we have good reason. It's better if you provide setXXX and getXXX methods, and let your fields to have private access:
    class DataSaved {
       // your current code appears here
       public void setInputName(String name) {
          InputName = name;
       public String getInputName() {
          return InputName;
    }Now, your cycle which retrieves the values should look something like this:
    for (int cntr=0;  cntr<myArray.length;  cntr++) {
       System.out.println(myArray[cntr].getInputName());
    }That myArray.length is an attribute of the arrays, which tells you the length of the array. Now, if you have to change the length later, you don't have to scrutinize your code, since the "magic number" appears in the code exactly once.
    You may read about the arrays and how they're handled in Java here:
    http://java.sun.com/docs/books/tutorial/java/data/arrays.html
    That ArrayList is another story; if you have succeeded with your array, come back and ask. "Preview": ArrayList is a way how to deal with arrays which might be expanded and shrunk as needed.
    You also might consider reading the tutorial about the collections (perhaps in a later time):
    http://java.sun.com/docs/books/tutorial/collections/index.html

  • Arrays,bubblesort, and binary search

    Hi I need help I have been working on this homework assignment for the past week and I can't seem to get it so if anyone can help me to figure out what is wrong I would reall grateful. Thanks ahead of time for the help.
    Here is what is required for the assignment and also the errors I am getting.
    Thanks!
    Write a program that sorts an integer array in ascending order and checks whether an integer entered by user is in the array or not. Please follow the following steps to complete the assignment:
    1. Declare and create a one-dimensional array consisting of 20 integers.
    2. Read 20 integers from the user to initialize the array. Use input dialog box and repetition statement.
    3. Build an output string containing the content of the array.
    4. Sort the array in ascending order using bubbleSort( ) and swap( ) methods. Then, append the content of the sorted array to the output string.
    5. Read an integer search key from the user;
    6. Use binarySearch( ) method to check whether the search key is in the array or not. Then, append the search result to the output string.
    7. Display the output string in a message box.
    Here is my code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SortSearch {
    public static void main (String args[])
    String input, ouput;
    int key;
    int index;
    int[] array=new int [20];
    input=JOptionPane.showInputDialog("Enter 20 Numbers");
    for(int counter=0; counter<array.length; counter++)
    output+=counter+"\t"+array[counter]+"\n";
    array(counter)=Integer.parseInt(input);
    JTextArea inputArea=new JTextArea();
    outputArea.setText(output);
    public void bubblesort(int array2[] )
    for(int pass=1; pass<array2.length; pass++){
    for(int element=0; element<array2.length-1; element++){
    if(array2[element]>array2[element+1])
    swap(array2, element, element+1);
    public void swap(int array3[], int first, int second)
    int hold;
    hold=array3[first];
    array3[first]=array3[second];
    array3[second]=hold;
    public void actionPerformed(ActionEvent actionEvent)
    String searchKey=actionEvent.getActionCommand();
    int element=binarySearch(array, Integer.parseInt(searchKey) );
    if(element!=-1)
    output.setText("Found value in element " + element);
    else
    output.setText("Value not found ");
    public int binary search(iny array2[], int key)
    int low=0;
    int high=array2.length-1;
    int middle;
    while(low<=high){
    middle=(low + high)/2;
    buildOutput(array2, low, middle, high);
    if(key==array[middle] )
    return middle;
    else if(key<array[middle] )
    high=middle-1;
    else
    low=middle+1
    return-1
    JOptionPane.showMessageDialog(null, outputArea);
    System.exit(0);
    } //end main
    } //end class
    Here is my errors
    C:\java>javac SortSearch.java
    SortSearch.java:27: illegal start of expression
    public void bubblesort(int array2[] )
    ^
    SortSearch.java:20: cannot resolve symbol
    symbol : variable output
    location: class SortSearch
    output+=counter+"\t"+array[counter]+"\n";
    ^
    SortSearch.java:22: cannot resolve symbol
    symbol : variable counter
    location: class SortSearch
    array(counter)=Integer.parseInt(input);
    ^
    SortSearch.java:25: cannot resolve symbol
    symbol : variable output
    location: class SortSearch
    outputArea.setText(output);
    ^
    SortSearch.java:25: cannot resolve symbol
    symbol : variable outputArea
    location: class SortSearch
    outputArea.setText(output);
    ^
    5 errors

    I am still having problems.
    Here is my code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SortSearch {
          public static void main (String args[]){
          String input, output;
          int key;
          int index;
          int[] array=new int [20];
          input=JOptionPane.showInputDialog("Enter 20 Numbers");
          for(int counter=0; counter<array.length; counter++)
            array(counter)=Integer.parseInt(input);
          JTextArea outputArea=new JTextArea();
          outputArea.setText(output);
            public void bubblesort(int array2[] )
              for(int pass=1; pass<array2.length; pass++){
                for(int element=0; element<array2.length-1; element++){
                  if(array2[element]>array2[element+1]) 
                    swap(array2, element, element+1);
                }  //end inner for
              }  //end outer for
            }  //end bubblesort 
            public void swap(int array3[], int first, int second)
              int hold;
              hold=array3[first];
              array3[first]=array3[second];
              array3[second]=hold;
            }  //end swap
            public void actionPerformed(ActionEvent actionEvent)
              String searchKey=actionEvent.getActionCommand();
              int element=binarySearch(array, Integer.parseInt(searchKey) );
              if(element!=-1)
                outputArea.setText("Found value in element " + element);
              else
                outputArea.setText("Value not found ");
            }  //end actionperformed
            JOptionPane.showMessageDialog(null, outputArea,"Comparisons");       
    }  //end classHere is my errors
    C:\java>javac SortSearch.java
    SortSearch.java:57: <identifier> expected
    JOptionPane.showMessageDialog(null, outputArea,"Comparisons");
    ^
    SortSearch.java:57: cannot resolve symbol
    symbol : class showMessageDialog
    location: class javax.swing.JOptionPane
    JOptionPane.showMessageDialog(null, outputArea,"Comparisons");
    ^
    SortSearch.java:19: cannot resolve symbol
    symbol : method array (int)
    location: class SortSearch
    array(counter)=Integer.parseInt(input);
    ^
    SortSearch.java:49: cannot resolve symbol
    symbol : variable array
    location: class SortSearch
    int element=binarySearch(array, Integer.parseInt(searchKey) );
    ^
    SortSearch.java:52: cannot resolve symbol
    symbol : variable outputArea
    location: class SortSearch
    outputArea.setText("Found value in element " + element);
    ^
    SortSearch.java:54: cannot resolve symbol
    symbol : variable outputArea
    location: class SortSearch
    outputArea.setText("Value not found ");
    ^
    6 errors
    Thanks ahead of time I still don't understand the stuff so I sometime don't understand what my errors are telling me so that is why I ask for your help so that maybe it will help make sense.

Maybe you are looking for