Populating an array of objects with a loop. Noob PHP question.

Hey guys,
   You are all such a great help! Here is another one for you, the simple code below should create an array of pizza objects (and it does) then display each object in order. However... for some reason each object in the array seems to inherit the properties of whatever the last object entered was.
This code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<?php
class pizza{
          public $price;
          public $description;
          public $name;
$menu2=fopen("pizzaMenu2.txt","r") or exit("System Error!");
$pizzas = array();
$arraypos=0;
//This loop does all of the READING and populating of variables
while(!feof($menu2))
            //First get the array position
                              $arraypos = (int)fgets($menu2);
          //Then Put in Title in title2 array
                              $pizzas[$arraypos2] = new pizza(0,0,0);
                              $pizzas[$arraypos2]->title = fgets($menu2);
                              $pizzas[$arraypos2]->description = fgets($menu2);
                              $pizzas[$arraypos2]->price = fgets($menu2);
  } //End of reading loop
//begin writing data
$arraypos=1;
while ($arraypos <=3){
          echo "the array is in position: ".$arraypos;
          echo "<br />";
          echo $pizzas[$arraypos2]->title;
          echo "<br />";
          echo $pizzas[$arraypos2]->description;
          echo "<br />";
          echo $pizzas[$arraypos2]->price;
          echo "<br />";
          $arraypos++;
}//end of writing data loop
fclose($menu2);
?>
<body>
</body>
</html>
returns this:
the array is in position: 1
Test Pizza Two
The same as one with an extra one, yum!
22.99
the array is in position: 2
Test Pizza Two
The same as one with an extra one, yum!
22.99
the array is in position: 3
Test Pizza Two
The same as one with an extra one, yum!
22.99
when it should return this:
the array is in position: 1
Test pizza One
Loaded with all that test pizza goodness! Lots and lots of ones 1111!
11.99
the array is in position: 2
Test Pizza Two
The same as one with an extra one, yum!
22.99
the array is in position: 3
Test Threeza!
Do you see what I did there? I added a three to pizza, hahaha, I am so punny.
33.33
using the following text file pizzaMenu2.txt:
1
Test pizza One
Loaded with all that test pizza goodness! Lots and lots of ones 1111!
11.99
3
Test Threeza!
Do you see what I did there? I added a three to pizza, hahaha, I am so punny.
33.33
2
Test Pizza Two
The same as one with an extra one, yum!
22.99
Now, I have done line by line testing and shown that the values are being entered into the proper objects in the proper array, but whatever goes in last overwrites all of the other objects, so in the end I have 3 objects in my array that are all the same. I am not sure what I am missing here.

Christ-Guard wrote:
Thanks! I majored in computer science
That helps enormously.
Christ-Guard wrote:
Also, I have never worked a CS job before and I've been out of school for 8 years, so I am better at remembering "This should work" then I am at "This is how I write this code".
If you have a good idea something should work, based on theory, then that's half the battle.
Its having no knowledge if something will work or not when it becomes a problem.

Similar Messages

  • Trouble creating and populating an array of objects.

    I'm trying to create/populate an array of objects with consisting of a {string, double, integer}, and am having trouble getting this theory to work in Java. Any assistance provided would be greatly appreciated. Following are the two small progs:
    public class HairSalon
    { private String svcDesc; private double price; private int minutes;
    //Create a constructor to initialize data members
    HairSalon( )
    svcDesc = " "; price = 0.00; minutes = 0;
    //Create a constructor to receive data
         HairSalon(String s, double p, int m)
         svcDesc = s; price = p; minutes = m;
    //Create methods to get the data members
    public String getSvcDesc( )
         return svcDesc;
    public double getPrice( )
         return price;
    public int getMinutes( )
         return minutes;
    public class SortSalon
         public static void main(String[ ] args)
         SortSalon [] sal = new SortSalon[6];
    //Construct 6 SortSalon objects
              for (int i = 0; i < sal.length; i++)
              sal[i] = new SortSalon();
    //Add data to the 6 SortSalon objects
         sal[0] = new SortSalon("Cut"; 10.00, 10);
         sal[1] = new SortSalon("Shampoo", 5.00, 5);           sal[2] = new SortSalon("Sytle", 20.00, 20);
         sal[3] = new SortSalon("Manicure", 15.00, 15);
         sal[4] = new SortSalon("Works", 30.00, 30);
         sal[5] = new SortSalon("Blow Dry", 3.00, 3);
    //Display data for the 6 SortSalon Objects
         for (int i = 0; i < 6 ; i++ )
         { System.out.println(sal[i].getSvcDesc( ) + " " + sal.getPrice( ) + " " + sal[i].getMinutes( ));
         System.out.println("End of Report");

    Hey JavaMan5,
    That did do the trick! Thanks for the assistance. I was able to compile and run the program after adding my sorting routine. Do you happen to see anything I can do to clean it up further, or does it look ok? Thanks again,
    Ironjay69
    public class SortSalon
         public static void main(String[ ] args) throws Exception
         HairSalon [] sal = new HairSalon[6];      
         char selection;
    //Add data to the 6 HairSalon objects
         sal[0] = new HairSalon("Cut", 10.00, 10);
         sal[1] = new HairSalon("Shampoo", 5.00, 11);      
         sal[2] = new HairSalon("Sytle", 20.00, 20);
         sal[3] = new HairSalon("Manicure", 15.00, 25);
         sal[4] = new HairSalon("Works", 30.00, 30);
         sal[5] = new HairSalon("Blow Dry", 3.00, 3);
    System.out.println("How would you like to sort the list?");
         System.out.println("A by Price,");
         System.out.println("B by Time,");
         System.out.println("C by Description.");
         System.out.println("Please enter a code A, B or C, and then hit <enter>");
              selection = (char)System.in.read();
    //Bubble Sort the Array by user selection
              switch(selection)
              case 'A':
              BubbleSortPrice(sal, sal.length);
                   break;
                   case 'a':
              BubbleSortPrice(sal, sal.length);
                   break;
                   case 'B':
              BubbleSortTime(sal, sal.length);                    break;
                   case 'b':
              BubbleSortTime(sal, sal.length);
                   break;
                   case 'C':
              BubbleSortService(sal, sal.length);
                   break;
                   case 'c':
              BubbleSortService(sal, sal.length);
                   break;
                   default:
              System.out.println("Invalid Selection, Randomly Sorted List!");
    //Display data for the 6 HairSalon Objects
              for (int i = 0; i < sal.length ; i++ )
         System.out.println(sal.getSvcDesc( ) + " " + sal[i].getPrice( ) + " " + sal[i].getMinutes( ));
              System.out.println("___________");
              System.out.println("End of Report");
    public static void BubbleSortPrice(HairSalon[] array, int len)
    // Sorts the items in an array into ascending order by price
    int a, b;
    HairSalon temp;
    int highSubscript = len - 1;
    for(a = 0; a < highSubscript; ++a)
         for(b= 0; b < highSubscript; ++b)
         if(array.getPrice() > array[b + 1].getPrice())
              temp = array[b];
              array[b] = array [b + 1];
              array[b + 1] = temp;
    public static void BubbleSortTime(HairSalon[] array, int len)
    // Sorts the items in an array into ascending order by time
         int a, b;
         HairSalon temp;
         int highSubscript = len - 1;
         for(a = 0; a < highSubscript; ++a)
              for(b= 0; b < highSubscript; ++b)
         if(array[b].getMinutes() > array[b + 1].getMinutes())
         temp = array[b];
         array[b] = array [b + 1];
         array[b + 1] = temp;
    public static void BubbleSortService(HairSalon[] array, int len)
    // Sorts the items in an array into ascending order by time
         int a, b;
         HairSalon temp;
         int highSubscript = len - 1;
         for(a = 0; a < highSubscript; ++a)
         for(b= 0; b < highSubscript; ++b)
         if(array[b].getSvcDesc().compareTo( array[b + 1].getSvcDesc()) > 0)
                   temp = array[b];
                   array[b] = array [b + 1];
                   array[b + 1] = temp;

  • Help populating an array of objects

    New here, trying to figure this out.
    I'm trying to create an array of objects, then populate the array defining fields. I stripped this down as far as i could to simplify the problem but I get the following error when I compile (i tweaked the carrot placment, formating issues i guess):
    PointsTest.java:41: ']' expected
    cubeArray[0] = new Point();
    ^
    PointsTest.java:41: invalid method declaration; return type required
    cubeArray[0] = new Point();
    ^
    2 errors
    My code:
    class PointsTest{
        public static void main(String[] args) {
                   //So far, this works.
                //convert 3 numbers to point coordinates held in temp variables
                float xT = (Float.valueOf(args[0])).floatValue();
                float yT = (Float.valueOf(args[1])).floatValue();
                float zT = (Float.valueOf(args[2])).floatValue();
                Point point1 = new Point(xT, yT, zT);
                point1.printXYZ(); 
    class Point {
        //A BASIC point class
        //fields defined
        float x, y, z;
        //a constructor that sets initial XYZ values
        Point(float startX, float startY, float startZ) {
                x = startX;
                y = startY;
                z = startZ;
        //a no argument constructor for defualt states
        Point () {
            x = 0;
            y = 0;
            z = 0;
        //method
        void printXYZ(){
            System.out.println("coordinates: " + x + " " + y + " " + z);
    class Cube{
         Point cubeArray[] =  new Point[9];
         cubeArray[0] = new Point();
    }I've looked for answers online without much luck, I'm not worried about using a loop to populate the array at the moment (you can do it one at a time, right?). Didn't see any obvious listings in the java tutorials about arrays of objects. Any help would be appreciated.

    You need to put operations inside of a method instead of just floating them around inside the top-level of your Cube class. The errors you are getting are related to the fact that only class data members or methods are supposed to be inside the top-level of a class definition.
    Something like this should get you started:
    class Cube{
            private Point[] cubeArray;
            public Cube(){
             cubeArray =  new Point[9];
    }Regards,
    -MF

  • Reading an Array of Objects from a .bin file!

    Hey, at the moment I'm creating a program whereby I write a set of objects onto a bin file, in this case an array of objects with a String name/county, and int population/area.... I'm not trying to read it back from the bin file and encountering trouble! I've managed to get it working using plain objects, however I want to be able to read in arrays of objects. The file itself compiles, however during running I get this error
    java.lang.NullPointerException
    at RecordFiles.CoastalRead.main(CoastalRead.java:33)
    at RecordFiles.__SHELL16.run(__SHELL16.java:6)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at bluej.runtime.ExecServer$3.run(ExecServer.java:774)
    Here is the program itself,
    import java.io.*;
    public class CoastalRead {
        public static void main(String[] args) {
            CoastalTowns towns[] = new CoastalTowns[50];
              towns[0] = new CoastalTowns();
              towns[1] = new CoastalTowns();
              towns[2] = new CoastalTowns();
              towns[3] = new CoastalTowns();
              towns[4] = new CoastalTowns();
              String name, county;
              int population, area;
            try {
                FileInputStream fileIn =
                        new FileInputStream("CoastalTownsBin.bin");
                ObjectInputStream in = new ObjectInputStream(fileIn);
                for (int i = 0; i < towns.length; i++){
                 towns[i] =(CoastalTowns) in.readObject();
                   System.out.println("Deserialized File...");
                       System.out.println("Name: " + towns.name);
              System.out.println("County: " + towns[i].county);
         System.out.println("Population: " + towns[i].population);
              System.out.println("Area: " + towns[i].area);
    in.close();
    fileIn.close();
    } catch (IOException i) {}
    catch (ClassNotFoundException c) {}
    +I'd appreciate a fast reply!+ And if someone needs the writing class I've used, I can post it asap.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    CoastalTowns towns[] = new CoastalTowns[50];
    towns[0] = new CoastalTowns();
    towns[1] = new CoastalTowns();
    towns[2] = new CoastalTowns();
    towns[3] = new CoastalTowns();
    towns[4] = new CoastalTowns();Why create an array with a size of 50 and then only fill 5 elements?
    Why bother filling any elements at all when you are reading the objects from a file?
    What happens if there are less than 50 objects in your file?
    I will assume CoastalTowns holds info about a single town, so why is it pluralised? Do you have a class called Dog or Dogs, Chair or Chairs, Person or People?
    } catch (IOException i) {}
    catch (ClassNotFoundException c) {}DO NOT swallow exceptions. At the very least put in a call to printStackTrace so you know if/when an exception occurs.
    I'd appreciate a fast reply!I typed as fast as I could but unfortunately I'm still and hunt and peck guy.

  • Property List error: Unexpected character b at line 1 / JSON error: JSON text did not start with array or object and option to allow fragments not set.

    Hi,
    I have a MBP 13' Late 2011 and Yosemite 10.10.2 (14C1514).
    Until yesterday, I was using Garmin ConnectIQ SDK and all was working fine.
    Yesterday, I've updated my system with latest security updates and Xcode updates too (Version 6.2 (6C131e)).
    Since, I can't launch the ConnectIQ simulator app, I have this message in console :
    8/04/2015 15:19:04,103 mds[38]: There was an error parsing the Info.plist for the bundle at URL Info.plist -- file:///Volumes/Leto/connectiq-sdk-mac-1.1.0_2/ios/ConnectIQ.bundle/
    The data couldn’t be read because it isn’t in the correct format.
    <CFBasicHash 0x7fa64f44e9a0 [0x7fff7dfc7cf0]>{type = immutable dict, count = 2,
    entries =>
      0 : <CFString 0x7fff7df92580 [0x7fff7dfc7cf0]>{contents = "NSDebugDescription"} = <CFString 0x7fa64f44f0a0 [0x7fff7dfc7cf0]>{contents = "Unexpected character b at line 1"}
      1 : <CFString 0x7fff7df9f5e0 [0x7fff7dfc7cf0]>{contents = "kCFPropertyListOldStyleParsingError"} = Error Domain=NSCocoaErrorDomain Code=3840 "The data couldn’t be read because it isn’t in the correct format." (Conversion of string failed.) UserInfo=0x7fa64f44eda0 {NSDebugDescription=Conversion of string failed.}
    I have looked at this file and it looks like a binary plist
    bplist00ß^P^V^A^B^C^D^E^F^G^H
    ^K^L^M^N^O^P^Q^R^S^T^U^V^W^X^Y^Z^[^\^]^^^_ !"$%&'()'+,^[\CFBundleNameWDTXcodeYDTSDKName_^P^XNSHumanReadableCopyrightZDTSDKBuild_^P^YCFBundleDevelopmentRegion_^P^OCFBundleVersi    on_^P^SBuildMachineOSBuild^DTPlatformName_^P^SCFBundlePackageType_^P^ZCFBundleShortVersionString_^P^ZCFBundleSupportedPlatforms_^P^]CFBundleInfoDictionaryVersion_^P^RCFBundleE    xecutableZDTCompiler_^P^PMinimumOSVersion_^P^RCFBundleIdentifier^UIDeviceFamily_^P^QDTPlatformVersion\DTXcodeBuild_^P^QCFBundleSignature_^P^ODTPlatformBuildYConnectIQT0611[iph    oneos8.1o^P-^@C^@o^@p^@y^@r^@i^@g^@h^@t^@ ^@©^@ ^@2^@0^@1^@5^@ ^@G^@a^@r^@m^@i^@n^@.^@ ^@A^@l^@l^@ ^@r^@i^@g^@h^@t^@s^@ ^@r^@e^@s^@e^@r^@v^@e^@d^@.V12B411RenQ1V14C109Xiphoneos    TBNDLS1.0¡#XiPhoneOSS6.0YConnectIQ_^P"com.apple.compilers.llvm.clang.1_0S8.1_^P^Tcom.garmin.ConnectIQ¡*^P^AW6A2008aT????^@^H^@7^@D^@L^@V^@q^@|^@<98>^@ª^@À^@Ï^@å^A^B^A^_^A?^AT^    A_^Ar^A<87>^A<96>^Aª^A·^AË^AÝ^Aç^Aì^Aø^BU^B\^B_^Ba^Bh^Bq^Bv^Bz^B|^B<85>^B<89>^B<93>^B¸^B¼^BÓ^BÕ^B×^Bß^@^@^@^@^@^@^B^A^@^@^@^@^@^@^@-^@^@^@^@^@^@^@^@^@^@^@^@^@^@^Bä
    I guess it is a normal format but my system seems to be unable to read binary plist ?
    I tried some stuff with plutil
    plutil -lint Info.plist
    Info.plist: Unexpected character b at line 1
    Same for convert
    plutil -convert xml1 Info.plist
    Info.plist: Property List error: Unexpected character b at line 1 / JSON error: JSON text did not start with array or object and option to allow fragments not set.
    I also try to download a fresh version of the connectIQ SDK and no changes.
    Any idea ?
    Thanks

    Step by step, how did you arrive at seeing this agreement?

  • Oracle 8i array DML operations with LOB objects

    Hi all,
    I have a question about Oracle 8i array DML operations with LOB objects, both CLOB and BLOB. With the following statement in mind:
    INSERT INTO TABLEX (COL1, COL2) VALUES (:1, :2)
    where COL1 is a NUMBER and COL2 is a BLOB, I want to use OCIs array DML functionality to insert multiple records with a single statement execution. I have allocated an array of LOB locators, initialized them with OCIDescriptorAlloc(), and bound them to COL2 where mode is set to OCI_DATA_AT_EXEC and dty (IN) is set to SQLT_BLOB. It is after this where I am getting confused.
    To send the LOB data, I have tried using the user-defined callback method, registering the callback function via OCIBindDynamic(). I initialize icbfps arguments as I would if I were dealing with RAW/LONG RAW data. When execution passes from the callback function, I encounter a memory exception within an Oracle dll. Where dvoid **indpp equals 0 and the object is of type RAW/LONG RAW, the function works fine. Is this not a valid methodology for CLOB/BLOB objects?
    Next, I tried performing piecewise INSERTs using OCIStmtGetPieceInfo() and OCIStmtSetPieceInfo(). When using this method, I use OCILobWrite() along with a user-defined callback designed for LOBs to send LOB data to the database. Here everything works fine until I exit the user-defined LOB write callback function where an OCI_INVALID_HANDLE error is encountered. I understand that both OCILobWrite() and OCIStmtExecute() return OCI_NEED_DATA. And it does seem to me that the two statements work separately rather than in conjunction with each other. So I rather doubt this is the proper methodology.
    As you can see, the correct method has evaded me. I have looked through the OCI LOB samples, but have not found any code that helps answer my question. Oracles OCI documentation has not been of much help either. So if anyone could offer some insight I would greatly appreciate it.
    Chris Simms
    [email protected]
    null

    Before 9i, you will have to first insert empty locators using EMPTY_CLOB() inlined in the SQL and using RETURNING clause to return the locator. Then use OCILobWrite to write to the locators in a streamed fashion.
    From 9i, you can actually bind a long buffer to each lob position without first inserting an empty locator, retrieving it and then writing to it.
    <BLOCKQUOTE><font size="1" face="Verdana, Arial, Helvetica">quote:</font><HR>Originally posted by CSimms:
    Hi all,
    I have a question about Oracle 8i array DML operations with LOB objects, both CLOB and BLOB. With the following statement in mind:
    INSERT INTO TABLEX (COL1, COL2) VALUES (:1, :2)
    where COL1 is a NUMBER and COL2 is a BLOB, I want to use OCIs array DML functionality to insert multiple records with a single statement execution. I have allocated an array of LOB locators, initialized them with OCIDescriptorAlloc(), and bound them to COL2 where mode is set to OCI_DATA_AT_EXEC and dty (IN) is set to SQLT_BLOB. It is after this where I am getting confused.
    To send the LOB data, I have tried using the user-defined callback method, registering the callback function via OCIBindDynamic(). I initialize icbfps arguments as I would if I were dealing with RAW/LONG RAW data. When execution passes from the callback function, I encounter a memory exception within an Oracle dll. Where dvoid **indpp equals 0 and the object is of type RAW/LONG RAW, the function works fine. Is this not a valid methodology for CLOB/BLOB objects?
    Next, I tried performing piecewise INSERTs using OCIStmtGetPieceInfo() and OCIStmtSetPieceInfo(). When using this method, I use OCILobWrite() along with a user-defined callback designed for LOBs to send LOB data to the database. Here everything works fine until I exit the user-defined LOB write callback function where an OCI_INVALID_HANDLE error is encountered. I understand that both OCILobWrite() and OCIStmtExecute() return OCI_NEED_DATA. And it does seem to me that the two statements work separately rather than in conjunction with each other. So I rather doubt this is the proper methodology.
    As you can see, the correct method has evaded me. I have looked through the OCI LOB samples, but have not found any code that helps answer my question. Oracles OCI documentation has not been of much help either. So if anyone could offer some insight I would greatly appreciate it.
    Chris Simms
    [email protected]
    <HR></BLOCKQUOTE>
    null

  • Serializing objects with arrays - JDBC

    Hello,
    Are there any known issues with serializing arrays into Blobs with JDBC?
    I have an object with a complex array. It’s basically name/value pairs, but the values
    can be arrays as well. The type of the values array can be of different types, i.e. string, Boolean, int, etc. These arrays are a unioned, and a discriminator identifies what type of array I have.
    Array (name, value.discriminator, value) where the value is also an array of some type.
    An example of some data would be.
    Name = ‘Employee Name’ values = { ‘Fred’} discriminator = StringType
    Name = ‘address’ values = { ‘addr1’, ‘addr2’, ‘addr3’} discriminator = StringType
    Name = ‘Insured’ values = {true} discriminator = booleanType
    Name = ‘Some_Int_values’ values = {1,2,3,4} discriminator = IntegerType
    Name = ‘SomeOther_Int_values’ values = {1,2,3,4} discriminator = IntegerType
    It does not need to be that complex… it might just be
    Name = ‘Employee Name’ values = { ‘Fred’} discriminator = StringType
    The issues I’m having is before I serialize the object and write it into a blob, I can repeat through the length of the outer array and print the value arrays. After I read the object for the blob, I cannot do this. It seems to have a problem identifying the discriminator type.
    Thanks!

    421780,
    Sounds like a good candidate for XML. Have you considered that? Have you seen Oracle's XML Technology Center?
    Good Luck,
    Avi.

  • Help on changing array elements with For loop

    Hi,
    I'm wondering if anyone can help me with this problem.  I'd like to be able to modify elements of an array with For loop.  In the attached VI, my goal is to have an array of [0 1 2 3 4 5], but instead what I've got is [2 2 2 2 4 5].  I initialized the array with a value of 2 to help me identify which elements are changing.  Can anyone help me pointing where my mistake is?  Thanks.
    Peter
    Attachments:
    Array test.vi ‏19 KB

    It's a classic issue for LV newbies. In this case you HAVE to use a
    shift register otherwise the modifications of previous cicles are lost.
    It's all easier than it's seems, see attached vi.
    bye,
    manga
    Attachments:
    Array test 2.vi ‏19 KB

  • Help with working with an array of objects

    Help!
    I'm trying to make an array of objects.
    I have a class named enemy.
    I want an array of enemy's.
    enemy[] Elist = new enemy[num];
    I now have an empty array.
    My question is, How do I initialize and retrieve vars from the objects?

    To create you need a loop that for each slot in the array you create a new enemy (should be Enemy) and store it in the array.
    Do you know how to access a single element in an array? ie the syntax to do that. If not then re-read your book or notes on arrays. I'm sure it mentions it there.
    Or you can just read the code provided above.
    Message was edited by:
    flounder

  • Sorting an array of numbers with loops

    Hi, i'm looking for a way to sort an array or numbers with loops.
    my array looks like this. int[] numbers = {5,2,7,9,1}
    i know how to use the "sort" method and i want to do it without the sort method, but i am not very clear on the logic behind it.
    by the end it should look like this, {1,2,5,7,9}
    i know 2 loops are used, can you please give me a logic to work with.
    i have started the loops but what to do inside???
    int temp;
    for (int i=0; i<numbers.length; i++){
    for (int j=1; j<numbers; j++){
    if (numbers<numbers[j])
    temp = numbers[i];
    Any suggestions i will be thankful for.
    thank you.

    fly wrote:
    no not really a homework question.. i want to improve my logic because it is very poor at the moment.. but i'm sure someone knows how to sort an array with loops only.Yes, we do know how to do it, I once wrote a heapsort in assembly code, as a real work project. But you rarely get a project like that the good ones were all done years ago.
    All the algorithms I suggested you look at use loops. the simplest and slowest is the bubble sort. This one runs by comparing values and swapping their locations, the wikipedia article http://en.wikipedia.org/wiki/Bubble_sort has the algorithm.

  • How to create a spidar chart (Radar chart) with an array collection object...

    Hi All,
              I need to create Spidar (Radar) chart in my application with the help of an array collection object........can any one help me ?? do i need to import any external library ???
    Please provide the required code for it .........
    Thanks in advance....

    You'll need to set the "series" property of the chart. This will be an array of BarSeries objects.
    You may also need to set the horizontalAxis and verticalAxis properties for the chart. (I forget if there are defaults for these.)

  • Creating a generic class with a constructor that takes an array of objects

    I am relatively new to java and want to build a quick utility class that can generate a Run Length Encoding of any object. The idea is to take an array of objects of type "O" and then encode a string of objects that are "equal" to each other as an integer that counts the number of such equal instances and a single copy of the instance. This has the potential to very quickly reduce the size of some objects that I want to store. I would like to implement this class as a generic.
    public class RunLengthEncoding<O> {
         private class RLEPair {
              private int length;
              private O object;
         public RunLengthEncoding(O[]) {
    }As you can see, I need to make a constructor that takes an array of type "O". Is this possible to do? I can't seem to find the right syntax for it.
    Thanks,
    Sean

    Sorry. Obvious answer:
    public RunLengthEncoding(O[] oarray) {Again, sorry for the noise.

  • How to list an array of objects using struts in jsp and ActionForm

    I am using the struts ActionForm and need to know how to display an Array of objects. I am assuming it would look like this in the ActionForm:
    private AddRmvParts addRmv[];
    But I am not sure how the getter and setter in the ActionForm should look. Should it be a Collection or an Iterator?
    I am thinking I need to use an iterator in the jsp page to display it.
    I am also wondering if the AddRmvParts class I have can be the same class that gets populated by the retrieval of data from the database. This class has 10 fields that need to display on the jsp page in 1 row and then multiple rows of these 10 fields.
    Thanks.

    Most probably the easiest way to make it accessible in your page is as a collection.
    ie
    public Collection getAddRmvParts()
    You can use the <logic:iterate> or a <c:forEach>(JSTL) tag to loop through the collection
    As long as the individual items in the collection provide get/set methods you can access them with the dot syntax:
    Example using JSTL:
    <c:forEach var="addRmvPart" items="${addRmvParts}">
      <c:out value="${addRmvPart.id} ${addRmvPart.name} ${addRmvPart.description}"/>
    </c:forEach>

  • An array of objects

    Hi,
    I'm having trouble creating an array of objects to store data I'm reading in from a text file.
    I have created a class called mssg, and as I read each line of the textfile in, I've created a method called setMsg that I'm using to populate the mssg object I've created.
    This works fine when I use this method on a single instance of a mssg object, but when I try to use the same code on a mssg object that's part of an array, I get an exception (and one that doesn't have any friendly error text)
    mssg ms = new mssg();  //this works as expected
    mssg msgs[] = new mssg [msgCounter]; //I believe the exception relates to how I'm declaring the array of objects here, but the exception doesn't occur until I try to assign data to an element of the arrayThe lines below are where the problem becomes apparent. The first object 'ms' gets assigned its values as I'd expect, however, the line below that tries to assign values to a mssg object in the msgs array, and I get an exception immediately.
    ms.setMsg(currMsg,mDt,mTm,mDir,mData);
    msgs[currMsg].setMsg(currMsg,mDt,mTm,mDir,mData);Can anyone tell me what I'm doing wrong in terms of declaring/assigning values to an array of objects?

    It's the following error: java.lang.NullPointerException
    Full error text if I take my code out of a try/catch loop is:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
            at FIXparserUI.jMenuLoadActionPerformed(FIXparserUI.java:301)
            at FIXparserUI.access$100(FIXparserUI.java:20)
            at FIXparserUI$3.actionPerformed(FIXparserUI.java:129)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
            at javax.swing.AbstractButton.doClick(AbstractButton.java:357)
            at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1170)
            at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1211)
            at java.awt.Component.processMouseEvent(Component.java:6038)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
            at java.awt.Component.processEvent(Component.java:5803)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4410)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2429)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)at the point that the following line of code is run:
    msgs[currMsg].setMsg(currMsg,mDt,mTm,mDir,mData);msgCounter is used to count the number of lines in the file (about 2300)
    I had hoped that what I was doing with this line:
    mssg msgs[] = new mssg [msgCounter];was create 2300 empty mssg records, ready to be populated from each line of data, however I have the feeling you're going to tell me I'm wrong.

  • Problem with a loop

    Hello All
    I'm working on a Flash Gallery and I'm having some issues
    with a loop and it's probably something simple I don't know so I
    thought I'd see if someone can help me.
    the problem is that once the thumbnail panel is populated the
    image I want to display from a rollover is no longer defined. As I
    mentioned I was hoping someone could shed some light on this.
    [code]
    // create the thumbnail panel
    var i = -1;
    while(++i<thumbList.length) {
    name = "item"+i;
    thumbs_mc.duplicateMovieClip(name,i);
    this[name]._x = i*spacing;
    this[name].contentPath = "children/" + thumbList
    // show the larger pic on rollover
    this[name].onRollOver = function() {
    picture.contentPath = "children/" + thumblist;
    [/code]
    by using this I get an error of: "error opening
    URL...undefined"

    mark2685 wrote:
    Well, the array of student objects is larger than 2, there are about 6 students so it would have to get the highest from TestScore 1 and the lowests from TestScore 2 out of all of the students, not just those 2. And I want the entire object stored in the chessTeam array. Does this make sense?No you're not reading my code right (BTW - add an open brace on the for loop top and set score2 to 101), or else I'm not understanding you requirements correctly. The student array can hold as many Students as needs be. You stated that you have only two scores that you care about and so that's the 1 and the 2. Based on the Student class you've shown us, this should work, but you'll have to try it before you know.

Maybe you are looking for

  • Syncing more than one photo album

    I am using iTunes to sync photos to my iPad. I have successfully synced one album to my iPad but when I try to upload another album it erases the photos already synced. How can I put all the desired photos on my iPad without erasing what I have alrea

  • How to implemenet "Edit in Browser" and "View in Browser" in custom ECB Menu

    Hi, i have build a custom ECB menu. I implemented for example "Edit in Microsoft xxx" Item successfully. setDocType(); if (currentItemAppName != "" && currentItemOpenControl != "") { strDisplayText = ""; if (currentItemAppName != " ") strDisplayText

  • IWeb Root Directory solution

    I had a question and saw some other discussions regarding publishing your iWeb '09 created site via FTP to a non-MobileMe webhost.  After some experimentation, I think I found one possible answer. You have to change your Site Name in iWeb to whatever

  • I the Dragon Dictate Plugin Safe to install? A warning message came up

    I recently received a message from Dragon Dictate (Nuance) asking me to install a new plugin. When I went to do so a warning message came up saying that the plugin was not fully compliant with standards and that it might allow outsiders to access my

  • IPhone 5 won't connect to Airport Extreme (1st gen) at end of extended network

    See the attached image below for my network setup... The Time Capsule is a 4th gen unit, the Airport Express (Mudroom) is a 2nd gen - both of which are dual band devices (5GHz *and* 2.4GHz at the same time). The Airport Extreme (Workshop) is a 1st ge