"count" in Arrays?

I have a question, my professor posted this question:
Write the body of the method select, shown below. The method traverses
the array arr and prints out all numbers that are both greater than or equal
to low and less than or equal to high.
For example, for the array below,
double[] a = { 2.0, 3.5, 6.8, 7.2, -10.0, 5.2, 16.3};
the call
select(a, 3.0, 7.0);
will print the numbers in a >= 3.0 and <= 7.0, i.e.
3.5
6.8
5.2
He then posted the answer:
      // print all items of arr between low and high, including
      // the borders
      public static void select(double[] arr, double low, double high)
          // print a title
          System.out.println("The items of the array >= " + low +
               " and <= " + high);
          // check  for empty array
          if (arr == null || arr.length == 0)
              System.out.println("The array is empty.");
              return;
          // we use an enhanced loop
          // we use a count to print the position of the number
          // in the sequence of numbers that satisfy that condition
          int count = 0;
          for ( double c: arr)
             // check if low <= c <= high
             if ( low <= c && c <= high)
                 count++;
                 System.out.println(count + ". " + c);
      } // end methodI understood everything except for "count" why exactly is count needed? Also, I don't get the output, did he make a mistake? Does it print the count number a period and the array number?

MiamiLoco wrote:
I understood everything except for "count" why exactly is count needed? Also, I don't get the output, did he make a mistake? Does it print the count number a period and the array number?Bingo. The count is simply for printing where in the array the number is. It's the same as doing this:
for(int i = 0; i < arr.length; i++){
   if ( low <= arr[i] && arr[i] <= high)
      System.out.println(i + ". " + arr);
}or for ( double c: arr){
// check if low <= c <= high
if ( low <= c && c <= high)
count++;
// System.out.println(count + ". " + c);
System.out.println("The number " + c + " is in the range and located in position " + count);
}The teacher's code wouldn't generate the same exact output he asked for, but it gets the job done.
Question: why didn't you ask the teacher about this bit? It's generally better to ask him than us!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Absolute Distinct count in Array -----Please help me out

    I'm running out of time and i have no clues to solve it.......can you please help me on it....
    The Absolute Distinct Count on Sorted Array is the count of
    distinct absolute values of elements of the array.
    For example, for the array.
    *[-5, -3, -1, 0, 3, 6]*
    the absolute distinct count is 5, because there is 5 distinct
    absolute values:
    *0, 1, 3, 5, 6*
    Write a function that computes the absolute distinct count
    of a given array.

    No, above code wouldn't work. Though it will give distinct count, but not absolute distinct count.
    Code to get absolute distinct count of elements in an array:
         public static void main(String args[]){
              int[] values = { -5, -3, -1, 0, 3, 6 };
              List<Integer> list=new ArrayList<Integer>();
              int tempVal=0;
              for(int val : values){
                   tempVal=Math.abs(val);
                   if(!list.contains(tempVal)){
                        list.add(tempVal);
              System.out.println("Absolute distinct count: "+list.size());
              System.out.println("Absolute distinct elements: "+list.toString());                    
         }Thanks,
    Mrityunjoy

  • Simple counter for array, help?

    I need to rewrite the ArrayList method for my class basically. I am working on the add method write now and the loop I have to count the number of integers and pass that in as the array list size isn't working. Here is the code:
    import javax.swing.*;
    import java.util.*;
    public class C {
      public static void main(String[] args) {
        int index = 0;
        String inputString = JOptionPane.showInputDialog(null, "Please enter so integers: ");
        Scanner console = new Scanner(inputString);
        while (console.hasNext() == true) {
          index++;
        System.out.println("Index : " + index);
    }It compiles but never prints the index, I think it is going into an infinite loop somehow.
    This is my first post here, hopefully this is the place to forum! :)

    while (console.hasNext() == true) {
    index++;
    It compiles but never prints the index, I think it is going into an infinite loop somehow. It sure is in an infinite loop. How are you expecting console.hasNext() to ever change in that loop if you're never consuming anything from console?

  • Counter To Array

    Hello,
    I have a numeric control that constantly changes value.
    I want to create a 1 row array of all these values.
    The array should contain the last 10 changes from the input and can delete any previous values.
    If for example my numeric control is a counter from 1 to 100. (1 2 3 4 5 6 ... 98 99 100)
    My array should always contain the last 10 digits
    Array after first 10 counts = 1 2 3 4 5 6 7 8 9 10
    Arrey in the middle = 43 44 45 46 47 48 49 50 51
    Array at the end = 91 92 93 94 95 96 97 98 99 100
    Any ideas?
    Thank you in advance.

    KLI wrote:
    Is there a possibilty to only store the value into the array at the moment it changes value instead of timed by the for loop iteration?
    Yes.
    (what is "constantly". How different to they need to be to be considered changed? Where is the value coming from?
    KLI wrote:
    For Loop with n=the number of values in the 1D array. (10)
    Use auto indexing to an Array indicator.
    That does not make a lot of sense. Can you show a picture of your code?
    LabVIEW Champion . Do more with less code and in less time .

  • Counting number of elements in an array which aren't empty?

    i tried using this method to count an array which has 100 elements but it doesn't go past the while statement which i cant figure out?
    public static void countCust()
    int cntr = 0;
    int z;
    for (int c = 0; c < 100; c++)
    while (customer[c].indexOf(':') != -1)
    cntr++;
    javax.swing.JOptionPane.showMessageDialog(null, "There are " + cntr + " customers on record");
    }

    Are you getting NullPointerExceptions?
    Are you sure customer[] has been allocated?
    Are you sure each element in the array is non-null?
    BTW, it's traditional to use variables in loops that are closer to their mathematical usage. I mean, for an array index, usually you'd use variables named i or j, unless the indices map to coordinates in space, in which case you'd use x, y, and z.
    If neither of these is applicable, use a variable with a more meaningful name.

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

  • A Bug in 11.1 array interface

    I have just encounter some code that runs fine in Oracle 9 to 10 but in 11.1 I am getting a different result.
    basically I have this SQL
    "INSERT INTO $table ( row_1, row_2, row_3) VALUES (?,?,?)"
    and bind all three to this array
    @var2 = (2,2,2,2,'s',2,2,2,2,2);
    using OCIBindByName and OCIBindDynamic and then execute them with
    OCIStmtExecute, with a mode (IN)
    of OCI_BATCH_ERRORS OCI_COMMIT_ON_SUCCESS (or 160)
    what happens is the commit does not happen in 11 but does happen in 9~10?
    Did something change in the execute in 11 or should I raise this up to a bug status??

    Ok here is a trace of the OCI Calls I use, and yes I the last one I give is a OCITransCommit
    st_execute_array INSERT count=10 (ARRAY(0x1a725c8) ARRAY(0x1a934c4) undef)
    OCIBindByName(876dad8,19cab00,8755e68,":p1",3,0,1,1,0,0,0,0,0,DATA_AT_EXEC)=SUCCESS
    OCIBindDynamic(876eda8,8755e68,19caadc, phs_in,19caadc,phs_out)=SUCCESS
    OCIBindByName(876dad8,1a27810,8755e68,":p2",3,0,1,1,0,0,0,0,0,DATA_AT_EXEC)=SUCCESS
    OCIBindDynamic(876ec68,8755e68,1a277ec,phs_in,1a277ec,phs_out)=SUCCESS
    OCIBindByName(876dad8,1a2bc18,8755e68,":p3",3,0,1,1,0,0,0,0,0,DATA_AT_EXEC)=SUCCESS
    OCIBindDynamic(876eb28,8755e68,1a2bbf4,phs_in,1a2bbf4,phs_out)=SUCCESS
    OCIStmtExecute(8755db0,876dad8,8755e68,10,0,0,0,160)=SUCCESS_WITH_INFO ->(OCI_BATCH_ERRORS|OCI_COMMIT_ON_SUCCESS)<--
    OCIAttrGet(876dad8,OCI_HTYPE_STMT,140f4ec,0,129,8755e68)=SUCCESS
    OCIErrorGet(8755e68,1,"<NULL>",140f48c,"ORA-24381: error(s) in array DML",1024,2)=SUCCESS
    OCIErrorGet(8755e68,2,"<NULL>",140f48c,"ORA-24381: error(s) in array DML",1024,2)=NO_DATA
    OCIAttrGet(876dad8,OCI_HTYPE_STMT,140f55c,0,73,8755e68)=SUCCESS
    st_execute_array 1 errors in batch.
    OCIHandleAlloc(8727940,140f578,OCI_HTYPE_ERROR,0,0)=SUCCESS
    OCIHandleAlloc(8727940,140f570,OCI_HTYPE_ERROR,0,0)=SUCCESS
    OCIParamGet(8755e68,2,876c3c0,140f578,0)=SUCCESS
    OCIAttrGet(876c968,OCI_HTYPE_ERROR,140f550,0,74,8755e68)=SUCCESS
    st_execute_array error in row 4.
    OCIErrorGet(876c968,1,"<NULL>",140f4cc,"ORA-01722: invalid number",1024,2)=SUCCESS
         OCIErrorGet(876c968,2,"<NULL>",140f4cc,"ORA-01722: invalid number",1024,2)=NO_DATA
    OCIHandleFree(876c3c0,OCI_HTYPE_ERROR)=SUCCESS
    OCIHandleFree(876c968,OCI_HTYPE_ERROR)=SUCCESS
    OCITransCommit(8755db0,8755e68,0)=SUCCESS
    st_execute_array warning: ORA-24381: error(s) in array DML (SUCCESS_WITH_
    INFO: error possibly near <*> indicator at char 56 in 'INSERT INTO test_ea( row_1, row_2,
    row_3) VALUES (:p1,:<*>p2,:p3)') [for Statement "INSERT INTO test_ea( row_1,  row_2, row_
    3) VALUES (?,?,?)"]
    and here is the code snipits but it is take out of a larger program so I will not run
    sb4
    phs_in(dvoid octxp, OCIBind bindp, ub4 iter, ub4 index,
         dvoid **bufpp, ub4 alenp, ub1 piecep, dvoid **indpp)
         phs_t phs = (phs_t)octxp;
    STRLEN phs_len;
    AV *tuples_av;
         SV *sv;
         AV *av;
         SV **sv_p;
         /* Check for bind values supplied by tuple array. */
         tuples_av = phs->imp_sth->bind_tuples;
         if(tuples_av) {
              /* NOTE: we already checked the validity in ora_st_bind_for_array_exec(). */
              sv_p = av_fetch(tuples_av, phs->imp_sth->rowwise ? (int)iter : phs->idx, 0);
              av = (AV*)SvRV(*sv_p);
              sv_p = av_fetch(av, phs->imp_sth->rowwise ? phs->idx : (int)iter, 0);
              sv = *sv_p;
              if(SvOK(sv)) {
              *bufpp = SvPV(sv, phs_len);
              phs->alen = (phs->alen_incnull) ? phs_len+1 : phs_len;
              phs->indp = 0;
              } else {
              *bufpp = SvPVX(sv);
              phs->alen = 0;
              phs->indp = -1;
    *alenp  = phs->alen;
    *indpp  = &phs->indp;
    *piecep = OCI_ONE_PIECE;
    if (!tuples_av && (index > 0 || iter > 0))
              croak(" Arrays and multiple iterations not currently supported (in %d/%d)", index,iter);
    return OCI_CONTINUE;
    sb4
    phs_out(dvoid octxp, OCIBind bindp,
         ub4 iter,     /* execution itteration (0...)     */
         ub4 index,     /* array index (0..)          */
         dvoid **bufpp,     /* A pointer to a buffer to write the bind value/piece.     */
         ub4 **alenpp,     /* A pointer to a storage for OCI to fill in the size     */
                   /* of the bind value/piece after it has been read.     */
         ub1 piecep,     / */
         dvoid **indpp,     /* Return a pointer to contain the indicator value which either an sb2     */
                   /* value or a pointer to an indicator structure for named data types.     */
         ub2 **rcodepp)     /* Returns a pointer to contains the return code.     */
    phs_t phs = (phs_t)octxp;     /* context */
    if (phs->desc_h) { /* a  descriptor if present  (LOBs etc)*/
              *bufpp  = phs->desc_h;
              phs->alen = 0;
    } else {
              SV *sv = phs->sv;
              if (SvTYPE(sv) == SVt_RV && SvTYPE(SvRV(sv)) == SVt_PVAV) {
              sv = av_fetch((AV)SvRV(sv), (IV)iter, 1);
              if (!SvOK(sv))
                        sv_setpv(sv,"");
              bufpp = SvGROW(sv, (size_t)(((phs->maxlen < 28) ? 28 : phs->maxlen)+1)/for null*/);
              phs->alen = SvLEN(sv);     /* max buffer size now, actual data len later */
    *alenpp = &phs->alen;
    *indpp  = &phs->indp;
    *rcodepp= &phs->arcode;
    *piecep = OCI_ONE_PIECE;
    return OCI_CONTINUE;
    static int
    do_bind_array_exec(sth, imp_sth, phs)
    SV *sth;
    imp_sth_t *imp_sth;
    phs_t *phs;
         dTHX;
    sword status;
    OCIBindByName_log(imp_sth->stmhp, &phs->bndhp, imp_sth->errhp,
    (text*)phs->name, (sb4)strlen(phs->name),
    0,
    phs->maxlen ? (sb4)phs->maxlen : 1, /* else bind "" fails */
    (ub2)phs->ftype, 0,
    NULL, /* ub2 alen_ptr not needed with OCIBindDynamic /
    0,
    0, /* max elements that can fit in allocated array */
    NULL, /* (ptr to) current number of elements in array */
    (ub4)OCI_DATA_AT_EXEC,
    status);
    if (status != OCI_SUCCESS) {
    oci_error(sth, imp_sth->errhp, status, "OCIBindByName");
    return 0;
    OCIBindDynamic_log(phs->bndhp, imp_sth->errhp,
    (dvoid *)phs, phs_in,
    (dvoid *)phs, phs_out, status);
    if (status != OCI_SUCCESS) {
    oci_error(sth, imp_sth->errhp, status, "OCIBindDynamic");
    return 0;
    return 1;
    static void
    init_bind_for_array_exec(phs)
    phs_t *phs;
         dTHX;
    if (phs->sv == &sv_undef) { /* first bind for this placeholder  */
    phs->is_inout = 0;
    phs->maxlen = 1;
    /* treat Oracle7 SQLT_CUR as SQLT_RSET for Oracle8 */
    if (phs->ftype==102)
    phs->ftype = 116;
    /* some types require the trailing null included in the length. */
    /* SQLT_STR=5=STRING, SQLT_AVC=97=VARCHAR */
    phs->alen_incnull = (phs->ftype==SQLT_STR || phs->ftype==SQLT_AVC);
    int
    st_execute_array(sth, imp_sth, tuples, tuples_status, columns, exe_count)
    SV *sth;
    imp_sth_t *imp_sth;
    SV *tuples;
    SV *tuples_status;
    SV *columns;
    ub4 exe_count;
         sword status, exe_status;
    int is_select = (imp_sth->stmt_type == OCI_STMT_SELECT);
    AV tuples_av, tuples_status_av, *columns_av;
    ub4 oci_mode;
    ub4 num_errs;
    int i,j;
    int autocommit = 1;
    SV **sv_p;
         phs_t **phs;
         SV *sv;
         AV *av;
    int param_count;
    char namebuf[30];
    STRLEN len;
    int outparams = (imp_sth->out_params_av) ? AvFILL(imp_sth->out_params_av)+1 : 0;
    tuples_av = (AV*)SvRV(tuples);
    /* Check the `columns' parameter. */
    if(SvTRUE(columns)) {
    if(!SvROK(columns) || SvTYPE(SvRV(columns)) != SVt_PVAV) {
    croak("ora_st_execute_array(): columns not an array peference.");
    columns_av = (AV*)SvRV(columns);
    } else {
    columns_av = NULL;
    /* Check the `tuples_status' parameter. */
    if(SvTRUE(tuples_status)) {
    if(!SvROK(tuples_status) || SvTYPE(SvRV(tuples_status)) != SVt_PVAV) {
         croak("ora_st_execute_array(): tuples_status not an array reference.");
    tuples_status_av = (AV*)SvRV(tuples_status);
    av_fill(tuples_status_av, exe_count - 1);
    /* Fill in 'unknown' exe count in every element (know not how to get
    individual execute row counts from OCI). */
    for(i = 0; (unsigned int) i < exe_count; i++) {
    av_store(tuples_status_av, i, newSViv((IV)-1));
    } else {
    tuples_status_av = NULL;
    /* Nothing to do if no tuples. */
    if(exe_count <= 0)
    return 0;
    param_count=c_NUM_PARAMS(imp_sth);/*returns the # of parameters on the imp_sth struct*/
         phs = safemalloc(param_count*sizeof(*phs));
    memset(phs, 0, param_count*sizeof(*phs));
         for(j = 0; (unsigned int) j < exe_count; j++) {
         sv_p = av_fetch(tuples_av, j, 0);
    if(sv_p == NULL) {
    Safefree(phs);
    croak("Cannot fetch tuple %d", j);
    sv = *sv_p;
    if(!SvROK(sv) || SvTYPE(SvRV(sv)) != SVt_PVAV) {
    Safefree(phs);
    croak("Not an array ref in element %d", j);
    av = (AV*)SvRV(sv);
    for(i = 0; i < param_count; i++) {
    if(!phs) {
    SV **phs_svp;
    sprintf(namebuf, ":p%d", i+1);
    phs_svp = hv_fetch(imp_sth->all_params_hv,
    namebuf, strlen(namebuf), 0);
    if (phs_svp == NULL) {
    Safefree(phs);
    croak("Can't execute for non-existent placeholder :%d", i);
    phs[i] = (phs_t*)(void*)SvPVX(*phs_svp); /* placeholder struct */
    if(phs[i]->idx < 0) {
    Safefree(phs);
    croak("Placeholder %d not of ?/:1 type", i);
    init_bind_for_array_exec(phs[i]); /*bind the value */
    sv_p = av_fetch(av, phs[i]->idx, 0);
    if(sv_p == NULL) {
    Safefree(phs);
    croak("Cannot fetch value for param %d in entry %d", i, j);
                   sv = *sv_p;
         /*check to see if value sv is a null (undef) if it is upgrade it*/
                   if (!SvOK(sv))     {
                        if(SvUPGRADE(sv, SVt_PV)){} /* For GCC not to warn on unused result */
                   else {
              SvPV(sv, len);
         /* Find the value length, and increase maxlen if needed. */
         if(SvROK(sv)) {
         Safefree(phs);
         croak("Can't bind a reference (%s) for param %d, entry %d",
         neatsvpv(sv,0), i, j);
         if(len > (unsigned int) phs[i]->maxlen)
         phs[i]->maxlen = len;
         /* Do OCI bind calls on last iteration. */
         if( ((unsigned int) j ) == exe_count - 1 ) {
         if(!do_bind_array_exec(sth, imp_sth, phs[i])) {
         Safefree(phs);
         Safefree(phs);
    /* Store array of bind typles, for use in OCIBindDynamic() callback. */
    imp_sth->bind_tuples = tuples_av;
    imp_sth->rowwise = (columns_av == NULL);
    oci_mode = OCI_BATCH_ERRORS;
    if(autocommit)
    oci_mode |= OCI_COMMIT_ON_SUCCESS;
         OCIStmtExecute_log(imp_sth->svchp, imp_sth->stmhp, imp_sth->errhp,
    exe_count, 0, 0, 0, oci_mode, exe_status);
         imp_sth->bind_tuples = NULL;
    if (exe_status != OCI_SUCCESS) {
              oci_error(sth, imp_sth->errhp, exe_status, ora_sql_error(imp_sth,"OCIStmtExecute"));
    if(exe_status != OCI_SUCCESS_WITH_INFO)
    return -2;
    OCIAttrGet_log(imp_sth, &num_errs, 0, OCI_ATTR_NUM_DML_ERRORS, status);
    if(num_errs && tuples_status_av) {
    OCIError row_errhp, tmp_errhp;
    ub4 row_off;
    SV *err_svs[2];
    /*AV err_av;/
    sb4 err_code;
    err_svs[0] = newSViv((IV)0);
    err_svs[1] = newSVpvn("", 0);
    OCIHandleAlloc_log(imp_sth->envhp, &row_errhp, OCI_HTYPE_ERROR, status);
    OCIHandleAlloc_log(imp_sth->envhp, &tmp_errhp, OCI_HTYPE_ERROR, status);
    for(i = 0; (unsigned int) i < num_errs; i++) {
    OCIParamGet_log(imp_sth->errhp, OCI_HTYPE_ERROR,
    tmp_errhp, (dvoid *)&row_errhp,
    (ub4)i, status);
    OCIAttrGet_log(row_errhp, OCI_HTYPE_ERROR, &row_off, 0,
    OCI_ATTR_DML_ROW_OFFSET, imp_sth->errhp, status);
    sv_setpv(err_svs[1], "");
    err_code = oci_error_get(row_errhp, exe_status, NULL, err_svs[1], debug);
    sv_setiv(err_svs[0], (IV)err_code);
    av_store(tuples_status_av, row_off,
    newRV_noinc((SV *)(av_make(2, err_svs))));
    OCIHandleFree_log(tmp_errhp, OCI_HTYPE_ERROR, status);
    OCIHandleFree_log(row_errhp, OCI_HTYPE_ERROR, status);
    /* Do a commit here if autocommit is set, since Oracle
    doesn't do that for us when some rows are in error. */
    if(autocommit) {
    OCITransCommit_log(imp_sth->svchp, imp_sth->errhp,
    OCI_DEFAULT, status);
    if (status != OCI_SUCCESS) {
    oci_error(sth, imp_sth->errhp, status, "OCITransCommit");
    return -2;
    if(num_errs) {
    return -2;
    } else {
    ub4 row_count = 0;
              OCIAttrGet_stmhp_log(imp_sth, &row_count, 0, OCI_ATTR_ROW_COUNT, status);
    return row_count;

  • Assign values from one array to another

    Hi, I am trying to solve a problem that asks that I assign values in the array that is input, which meet a certain criteria, into another array. isFunny will determine if a given integer is funny, countFunnies will determine how many integers in the given array are funny or not. collectFunnies should assign elements from the first array that are funny into the new array. Please take a look at the code, I am at a loss, everything looks good to me.
    public class BatchOne
    public boolean isFunny(int x) {
    if (x%2 == 0) {return true;}
    else {return false;}
    public int countFunnies(int[] a) {
    int count = 0;
    for (int funCheck :a) {
    if(isFunny(funCheck)) {
    count++;
    return count;
    public int[] collectFunnies(int[] a) {
    int count = 0;
    int i = 0;
    for (int funCheck :a) {
    if(isFunny(funCheck)) {
    count++;
    int[] array = new int[count];
    for (int funCheck : a) {
    if(isFunny(funCheck)) {
    array[i] = funCheck;
    i++;
    return array;
    Thanks,
    T

    Ok, I am new to programming and posting so likely need some refinement to my posts.
    I am using BlueJ to write my code, the above posted is my entire code. It is compiling correctly but when I run, the return was giving me back something strange, I am not sure if I can post a screenshot because it would be hard to explain.
    However, upon further review, it seems that there are some intricacies with BlueJ that I am obviously not used to, because when I select to inspect the return, the program seems to be returning an array of values that is in line with my intended goal.
    Thank you for your guidance in terms of how to use the forums.
    T

  • Filtering and calculating averages of array subsets

    I've got a 2-D array coming out of a loop and I need to calculate average for subsets corresponding to iterations 0-9, 10-19, etc..  Additionally, I need to filter out values above and below acceptable limits before calculating average.  Any suggestions for how to approach this?
    Solved!
    Go to Solution.

    My suggestion is to slog through each array subset, use a for loop to add up the values you want, keep track of the number of values, then divide out for the average. 
    Every tenth reading you could clear the sum and counts.
    The results would be saved in an array that only adds a value every tenth loop.
    You could keep track of the one to ten value separately from the number of values accepted ( a.k.a. Filtering).
    So my slog suggestion would be a for loop, two counters ( # accepted values and one to ten count), an array to store the averages and a numeric to hold the sum.
    The filter criteria would produce a Boolean that would toggle adding to the sum and adding to the # accepted values.
    The Sum and the counters need to be shift registers, and as I mentioned, there would be some logic to clear these shift registers every time the 'one to ten' count got to ten
    Mark Ramsdale

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

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

  • Frequency Count

    I was given the task to create a line of code that would count the frequency of each number, boldarray[counter]*bold*. I'm stuck because the numbers are randomized and I am suppose to find the count for each of the random numbers, seeing as only 10 of 100 numbers are being printed I am confused. I am also aware of the lines in there that aren't being printed. Please help.
    public class InitArrayy {
         public static void main ( String args[] )
              int array[];
              int fCount=0;
              int count = 0;
              array  = new int[ 11 ];
               for(int counter = 1; counter < array. length; counter++ )
                    array[counter] = (int) (Math.random()*100);
                    count = counter;
                    System.out.printf("\t Frequency=%5d",array[counter]);
                    if(array[counter]==5) fCount++;
                    if(counter%2==0)
                    System.out.printf("\t array(%3d)=%3d\n", counter,array[counter]);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
                    else
                    System.out.printf("\t array(%3d)=%3d\n", counter,array[counter]);
         }

    Please explain what in your mind was each line of the below to do?
                            if(array[counter]==5) fCount++;
                    if(counter%2==0)
                    System.out.printf("\t array(%3d)=%3d\n", counter,array[counter]);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
                    else
                    System.out.printf("\t array(%3d)=%3d\n", counter,array[counter]);

  • Sorting an array of integers into ascending order

    Today I decided to blow the cobwebs off my old laptop and see what I could remember from my Java days.
    As a task for myself to see what I could remember, I decided to try and write a program that does the following:
    - Declares an array of 4 integers
    - Sorts the array into ascending order, from lowest to highest.
    - Prints on screen the sorted array.
    After an hour or so I finally cracked it, and ended up with a working program. Here she is:
    public class Sorting_arrays_1
        public static void main()
           int [] array = {4,3,7,1};
           //A variable used to help with swopping values
           int temporary;
              //finds the smallest number out of elements 0, 1, 2, and 3 of the array, then moves it to position 0
              for (int count = 0; count<array.length;count++)
                int smallestNumber = array[0];
                if (array[count] < smallestNumber)
                    smallestNumber = array[count];
                    temporary = array[0];
                    array[0]=array[count];
                    array[count]=temporary;
             //finds the smallest number out of elements 1, 2, and 3 of the array, then moves it to position 1
             for (int count = 1; count<array.length;count++)
                int smallestNumber = array[1];
                if (array[count] < smallestNumber)
                    smallestNumber = array[count];
                    temporary = array[1];
                    array[1]=array[count];
                    array[count]=temporary;        
              //finds the smallest number out of elements 2 and 3 of the array, then moves it to position 2
              for (int count = 2; count<array.length;count++)
                int smallestNumber=array[2];
                if (array[count] < smallestNumber)
                    smallestNumber = array[count];
                    temporary = array[2];
                    array[2]=array[count];
                    array[count]=temporary;     
             //prints the array in ascending order
             for (int count=0; count<array.length;count++)
                 System.out.print(array[count] + " ");
    }Could this code be simplified though? Maybe with a for loop?
    I mean, it does the job, but it looks so clumbsy and inefficient... Imagine how much code I would need if I wanted to sort 1000 numbers..

    Use bubble sort if u want a quick fix
    public static void bubbleSort(int [] a)
    for(int i=0; i<a.length-1; i++)
         for(int j=0; j<a.length-1-i; j++)
              if(a[j]>a[j+1])
                   int temp = a[j];
                   a[j]=a[j+1];
                   a[j+1]=temp;
    Or use Merge sort if u want better run time... ie.(N log N)

  • Breaking up a String array

    Hi guys!
    I have been working on this for a while! I have an assignment which requires:
    -take input of a seven digit integer
    - break this number apart and perform calculations in order to "encrypt" the number.
    -etc..
    I thought I should break the string up first, then convert each element to an int for calculations.
    I am sure there is a better way to do this.
    Could I use a String Tokenizer? How would I do that?
    Thanks!!
    Here's what I have so far:
    import javax.swing.*;
    public class Assignment3 {
      public static void main( String args[] ) {
        String choiceString = "",
        output = "",
        stringArray[] = new String[7];
        int intArray[] = new int[7],
        choiceInt;
        while ( choiceString != null ) {
          // prompt user to input a seven digit integer
          choiceString=JOptionPane.showInputDialog("Please     enter the number corresponding to your choice:\n1.Encryption\n2.Decryption\n3.Exit");
          choiceInt = Integer.parseInt( choiceString );
         if( choiceInt != 1 || choiceInt != 2 || choiceInt != 3)
            JOptionPane.showMessageDialog( null, "Invalid selection", "Error",
            JOptionPane.ERROR_MESSAGE );
          // 1=encrypt 2=decrypt 3=exit
          switch ( choiceInt ) {
            case 1:
             stringArray = JOptionPane.showInputDialog( "Please enter a seven digit number:" ) ;
              intArray = convert( stringArray );    // converts string to int
              digitSwap1( intArray );   
              nineModTen( intArray );
              digitSwap2( intArray );
              output += "Original: " + input + "\nOutput: " +  intArray;
              break;
            case 2:
              stringArray = JOptionPane.showInputDialog( "Please enter an encrypted number: " );
              intArray = convert( stringArray );
              digitSwap2( intArray );
              decrypt( intArray );
              digitSwap1( intArray );
              output += "Decrypted: " + input + "\nOutput: " + intArray;
              break;
            case 3:
              output += "Thank you, have a nice day";
              break;
            default:
              JOptionPane.showMessageDialog( null, "Please make a selection", "Error",
              JOptionPane.ERROR_MESSAGE );
              break;
          } // end switch
          JOptionPane.showMessageDialog( null, output, "Results",
          JOptionPane.INFORMATION_MESSAGE );
        } // end loop
        System.exit(0);
      } // end main
      public static void digitSwap1( int array[] )
        int digit1,digit2,digit3,digit4,digit5,digit6,digit7;
        digit1 = array[0];
        digit2 = array[1];
        digit4 = array[3];
        digit5 = array[4];
        digit6 = array[5];
        digit7 = array[6];
        array[0] = digit7;
        array[1] = digit6;
        array[2] = digit5;
        array[4] = digit3;
        array[5] = digit2;
        array[6] = digit1;
        } // end digitSwap1
      public static void nineModTen( int array[] )
        int x = 0;
        while ( x <= 6 ) {
          array[x] = ( array[x] + 9 ) % 10;
          x++;
        } // end loop
      }  // end nineModTen
      public static void digitSwap2( int array[] )
        int digit1,digit2,digit3,digit4,digit5,digit6,digit7;
        digit1 = array[0];
        digit2 = array[1];
        digit3 = array[2];
        digit4 = array[3];
        digit5 = array[4];
        digit6 = array[5];
        array[0] = digit2;
        array[1] = digit1;
        array[2] = digit4;
        array[3] = digit3;
        array[4] = digit6;
        array[5] = digit5;
      }  // end digitSwap2
      public static void decrypt( int array[] )
        int x = 0;
        while ( x <= 6 ) {
          if ( array[x] < 9 )
            array[x] += 1;
          else
            array[x] = 0;
          x++;
        }  // end loop
      } // end decrypt
      public static int[] convert( String array1[] )
        int array2[] = new int[7];   
        int count = 0;
        while ( count <= 6 ) {
          array2[count] = Integer.parseInt( array1[count] );
          count ++;
        } // end loop
        return( array2 );
        } // end convert
    } // end class

    I have solved my problem! The real problem was that I
    was trying to output my resulting int array like this:
    output = "result: " + intArraybut I discovered that when I concatenated each individual
    element in the array, it worked fine:
    output = "result: " + array[0] + array[1] ....Also, I found an easy way to break up the input. Rather
    than use the charAt() method to extract each digit, and
    then convert for calculation, I converted the String to int
    and then, in a loop, extracted each digit from last to
    first by: (array[count] = number% 10), then (number = number / 10).
    Thanks everyone for your help! I hope this will help
    someone else too. Below is the working code.
    ; > -HB
    // this program takes a 7 digit input and "encrypts" it
    // by 1st, swapping some of the digits, 2nd, add nine
    // and mod ten to each digit, 3rd, swapping digits again.
    import javax.swing.*;
    public class Assignment3 {
      public static void main( String args[] ) {
        String choiceString = "",
        output = "",
        input;
        int number;
        int intArray[] = new int[7],
        choiceInt = 0;
        while ( choiceString != null ) {
          // prompt user to choose an option
          choiceString=JOptionPane.showInputDialog("Please enter the number corresponding to your choice:\n1.Encryption\n2.Decryption\n3.Exit");
          choiceInt = Integer.parseInt( choiceString );
          // 1=encrypt 2=decrypt 3=exit
          switch ( choiceInt ) {
              case 1:
              input = JOptionPane.showInputDialog( "Please enter a seven digit number:" );
              number = Integer.parseInt( input );
              intArray = convert( number );    // extract each digit
              intArray = digitSwap1( intArray );   
              nineModTen( intArray );
              intArray = digitSwap2( intArray );
              output = "Original: " + input + "\nOutput: " + intArray[0] +
                       intArray[1] + intArray[2] + intArray[3] +
                       intArray[4] + intArray[5] + intArray[6];
              JOptionPane.showMessageDialog( null, output, "Results",
              JOptionPane.INFORMATION_MESSAGE );
              break;
            case 2:
              input = JOptionPane.showInputDialog( "Please enter an encrypted number: " );
              number = Integer.parseInt( input );
              intArray = convert( number );
              intArray = digitSwap2( intArray );
              decrypt( intArray );
              intArray = digitSwap1( intArray );
              output = "Decrypted: " + input + "\nOutput: " + intArray[0] +
                       intArray[1] + intArray[2] + intArray[3] + intArray[4] +
                       intArray[5] + intArray[6];
              JOptionPane.showMessageDialog( null, output, "Results",
              JOptionPane.INFORMATION_MESSAGE );
              break;
            case 3:
              break;
            default:
              JOptionPane.showMessageDialog( null, "Please make a valid selection", "ERROR", JOptionPane.ERROR_MESSAGE);
              break;
          } // end switch
          if ( choiceInt == 3 )
            break;
          } // end loop
          JOptionPane.showMessageDialog( null, "Thank you, Have a nice day!", "EXIT",
          JOptionPane.PLAIN_MESSAGE );
        System.exit(0);
      } // end main
        public static int[] convert( int num )
          int array[] = new int[7];
          int count = 6;
          while ( count >= 0 ) {
            array[ count ] = num % 10;
            num = num / 10;
            count --;
          return array;
      } // end convert
      public static int[] digitSwap1( int array[] )
        int digit1,digit2,digit3,digit5,digit6,digit7;
        digit1 = array[0];
        digit2 = array[1];
        digit3 = array[2];
        digit5 = array[4];
        digit6 = array[5];
        digit7 = array[6];
        array[0] = digit7;
        array[1] = digit6;
        array[2] = digit5;
        array[4] = digit3;
        array[5] = digit2;
        array[6] = digit1;
        return array;   
      } // end digitSwap1
      public static void nineModTen( int array[] )
        int count = 0;
        while ( count < 7 ) {
          array[count] = ( array[count] + 9 ) % 10;
          count++;
        } // end loop
      }  // end nineModTen
      public static int[] digitSwap2( int array[] )
      int digit1,digit2,digit3,digit4,digit5,digit6;
        digit1 = array[0];
        digit2 = array[1];
        digit3 = array[2];
        digit4 = array[3];
        digit5 = array[4];
        digit6 = array[5];
        array[0] = digit2;
        array[1] = digit1;
        array[2] = digit4;
        array[3] = digit3;
        array[4] = digit6;
        array[5] = digit5;
        return array;
      }  // end digitSwap2
      public static void decrypt( int array[] )
        int count = 0;
        while ( count <= 6 ) {
          if ( array[count] < 9 )
            array[count] += 1;
          else
            array[count] = 0;
          count++;
        }  // end loop
       } // end decrypt
      } // end class

  • How to count columns

    My CF app. start with validating if the text file I'm processing contain the right mount of allowable column.
    Each row of my text file should consist of 100 columns, each column is separated by a tab delimiter
    How can I count these columns in CF after user uploading the text file. Please help!

    Hi Dan, thanks for helping. Here is what I did and did not quite working as expected because the end of list row got included as an empty element in my array
    For this test, so that I can see the result on my cfdump, I replaced tab delimiters with bar (|) delimiters.
    John|Bates| | |123 test Road|Catonsville |MD|21212 | || | | || |X
    Betty|Smith| | |345 My Road|Baltimore|MD|21218 | || | | || |X
    Here is what I did: 
    <cffile action="READ" file="/www/fileLocation/#session.userid#/#FileName#" variable="MyFile">
    <CFSET fileContents = #Replace(MyFile,chr(9),"|", "ALL")#>
    <cfset arr_Rows = #ListToArray(fileContents,crlf,TRUE)#>
    <cfdump var="#arr_Rows#"> ------------> I saw extra array elements with blank value after array element X
                                                             So it looks like: 
    | John|Bates| | |123 test Road|Catonsville |MD|21212 | || | | || |X  
    |------------------------------------------------------------------------------------------
    | blank value element
    |------------------------------------------------------------------------------------------ -
    || Betty|Smith| | |345 My Road|Baltimore|MD|21218 | || | | || |X
    |----------------------------------------------------------------------------------------- -
    |---------------------------------------------------------------------------------------- ---
    || blank value element
    |---------------------------------------------------------------------------------------- ---
    I'm looping each of the above element to count the column. (See below)
    and when it reach blank element, it throw error because there is no column.
    <CFLOOP index="i" array="#arr_Rows#">  </CFLOOP>   
         <CFIF ArrayLen(ListToArray(i,"|",TRUE)) EQ 14>        <cfdump var="#ArrayLen(ListToArray(i,"|",TRUE))#> ----------> In here the count and array looks correct                                                        
                                                             John
                                                             Bates
                                                             123 test Rd
                                                             Catonsville
                                                             MD
                                                             21212
                                                             X
      <CFELSE>
            <cfdump var="#ArrayLen(ListToArray(i,"|",TRUE))#> -------> this is where it caught the blank element, which is the last element that should not be there.
        </CFIF>

Maybe you are looking for

  • Multiple iphones using one itunes account

    I'm fairly new to the itunes world and was wondering about the ability to sync multiple iphones to a single itunes account. I have the iphone 4s and have it synced with my itunes account...my boyfriend recently left the dark ages and is now using my

  • Safari 4.0 Beta always crashing on Windows XP...

    I had a Windows XP partition (which ended up getting very bad malware, so I deleted it and started a new one) on my MBP, and Safari 4.0 Beta always crashed on it (this was before the malware infection). Now, jump to my new Windows XP partition: so fa

  • How do I find the iTunes version on my iPad?

    How do I find the iTunes version on my IPAD?

  • MBP does not come back after hybernation

    Hello everyone, I am enjoying my MBP except for one problem. It does not come back after it hybernates sometimes. I hit a key, hear the superdrive do it's "thing" and then after much waiting (approximately over 10 minutes) no picture or video on the

  • Correspondance type

    Hello All, When a correspondance type is used to request the open items list of vendor, there is no document reference number is being displayed in the out put. Can anyone please suggest me where should I do the changes. Thank you Srinivas