Storing details of objects in an array in a class

Hi there
New to all this class malarkey so having some teething
problems and could do with some help.
I have written a function to display 10 stars on screen using
attachMovie
i.e
var vStar_Object = attachMovie(vLinkage_Name, vInstance_Name,
vDepth);
I later need to access these star objects to enable me to
animate them to certain positions on screen.
I am therefore trying to create a starManager class to store
the details of these star objects.
Here is my class so far:
class classes.starManager {
// Constructor
public function starManager() {
trace ("starManager class constructor");
var List_Of_Star_Objects:Array = new Array();
// Add Star Object
public function
Add_Star_Object(passed_Star_Object:Object):Void {
List_Of_Star_Objects.push(passed_Star_Object);
I have created an instance of this class as follows:
myStarManager = new starManager();
Therefore in the loop that creates my 10 star objects I call
the function "Add_Star_Object" as follows:
myStarManager.Add_Star_Object(vStar_Object);
However I am getting the following error message:
There is no method with the name 'List_Of_Star_Objects'.
List_Of_Star_Objects.push(passed_Star_Object);
Any ideas what I am doing wrong here or suggestions as how
this is best done. Basically I need to store some reference to my
star objects and I do not want to use globals.
Thanks in advance
Paul

Before the constructor method
// Class variables
private var List_Of_Star_Objects:Array();
In the constructor method
change var List_Of_Star_Objects:Array = new Array();
to List_Of_Star_Objects:Array = new Array();
or this.List_Of_Star_Objects:Array = new Array();
I recommend not capitalizing the first letter of variable
names. Initial
caps normally indicates a class name.
Lon Hosford
www.lonhosford.com
Flash, Actionscript and Flash Media Server examples:
http://flashexamples.hosfordusa.com
May many happy bits flow your way!
"ChuckyLeFrek" <[email protected]> wrote in
message
news:[email protected]...
> Hi there
>
> New to all this class malarkey so having some teething
problems and could
> do
> with some help.
>
> I have written a function to display 10 stars on screen
using attachMovie
>
> i.e
>
> var vStar_Object = attachMovie(vLinkage_Name,
vInstance_Name, vDepth);
>
> I later need to access these star objects to enable me
to animate them to
> certain positions on screen.
>
> I am therefore trying to create a starManager class to
store the details
> of
> these star objects.
>
> Here is my class so far:
>
> #############################
>
> class classes.starManager {
>
> // -----------
> // Constructor
> // -----------
>
> public function starManager() {
>
>
> trace ("starManager class constructor");
>
> var List_Of_Star_Objects:Array = new Array();
>
>
>
> }
>
>
>
> // ---------------
> // Add Star Object
> // ---------------
>
> public function
Add_Star_Object(passed_Star_Object:Object):Void {
>
>
> List_Of_Star_Objects.push(passed_Star_Object);
>
>
> }
>
>
>
> }
>
> #################################
>
> I have created an instance of this class as follows:
>
> myStarManager = new starManager();
>
> Therefore in the loop that creates my 10 star objects I
call the function
> "Add_Star_Object" as follows:
>
> myStarManager.Add_Star_Object(vStar_Object);
>
>
> However I am getting the following error message:
>
> There is no method with the name 'List_Of_Star_Objects'.
> List_Of_Star_Objects.push(passed_Star_Object);
>
>
> Any ideas what I am doing wrong here or suggestions as
how this is best
> done.
> Basically I need to store some reference to my star
objects and I do not
> want
> to use globals.
>
> Thanks in advance
>
> Paul
>
>
>

Similar Messages

  • Help needed for storing and sorting objects.

    Hello
    I have an assignment and it is to create a guessing game, here is the question,
    In this assignment you are to write a game where a user or the computer is to guess a random
    number between 1 and 1000. The program should for example read a guess from the keyboard, and
    print whether the guess was too high, too low or correct. When the user has guessed the correct
    number, the program is to print the number of guesses made.
    The project must contain a class called Game, which has only one public method. The method must
    be called start(), and, when run it starts the game. The game continues until the user chooses to
    quit, either at the end of a game by answering no to the question or by typing 'quit' instead of a
    guess. After each game has been played, the program is to ask the user for a name and insert this
    together with the number of guesses into a high score list. When a game is started the program
    should print the entire high score list, which must be sorted with the least number of guesses first
    and the most last. Note, the list must be kept as long as the game-object is alive!
    each score also
    consists of the game time. In case there are two high scores with the same number of guesses, the
    game time should decide which is better. The game time starts when the first guess is entered and
    stops when the correct guess has been made. There should also be input checks in the program so
    that it is impossible to input something wrong, i.e. it should be impossible to write an non-numeric
    value then we are guessing a number, the only allowed answers for a yes/no question is yes or no,
    every other input should yield an error message an the question should be printed again.
    I understand how to code most of it, except I am not sure how to store the playerName, playerScore, playerTime and then sort that accordingly.
    I came across hashmaps, but that wont work as the data values can be the same for score.
    Is it only one object of lets say a highScore class, and each time the game finishes, it enters the values into an arrayList, I still dont understand how I can sort the array all at once.
    Should it be sorted once for score, then another array created and sorted again, I dont get it I am confused.
    Please help clarify this.

    Implode wrote:
    We had the arrayList/collections lecture today.
    I asked the teacher about sorting objects and he started explaining hashmaps and then he mentioned another thing which we will only be learning next term, I'm sure we must only use what we have learned.
    How exactly can this be done. I have asked a few questions in the post already.
    ThanksWell, there was probably a gap in the communication. Hash maps (or hash tables, etc.) are instance of Map. Those are used to locate a value by its unique key. Generally, to speed up access, you implement a hashing function (this will be explained hopefully in class). Think of name-value pairs that are stored where the name is unique.
    Contrast this with items that are sorted. Any List can be sorted because its elements are ordered. An ArrayList is ordered, generally, by the order you inserted the elements. However, any List can be given its own ordering via Comparable or Comparator. You can't do this with an ordinary Map. The purpose of a Map is speedy access to the name-value pairs, not sorting. The List likewise has different purposes, advantages, disadvantages, etc. List can be sorted.
    A Map is generally similar to a Set. A Set is a vanilla collection that guarnatees uniqueness of each element (note, not name-value pairs, but simple elements). There is one concrete class of Map that can be sorted, TreeMap, but I doubt your professor was referring to that. The values or the keys can be returned from the Map and sorted separately, but again, I doubt he was referring to that.
    Take a look at the Collections tutorial here on this site or Google one. It is fairly straightforward. Just keep in mind that things (generally) break down into Set, Map and List. There are combinations of these and different flavors (e.g., Queue, LinkedHashMap, etc.) But if you can learn how those three differ, you will go a long way towards understanding collections.
    (Oh, and be sure to study up on iterators.)
    - Saish

  • How do I insert an object in an array?

    How can I insert an object in an array of variable size?
    I input two numbers from keyboard
    1
    2that form the following object (Pair)
    (1,2)
    how can I add such objects to an array
    private Pair s[];
    e.g.
    public PairList(int x){
    top = -1;
    s = new Pair[x];
    }//constructor
    public void getPairs()throws FullException{
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    try{
    a=input.readLine();b=input.readLine();
    }//try
    catch(IOException e){System.out.println("Can't read input");}//catch
    int x=0;
    int y=0;
    try{
    x=Integer.parseInt(a);}//try
    catch(NumberFormatException e){}
    try{
    y=Integer.parseInt(b);}//try
    catch(NumberFormatException e){}
    Pair k=new Pair(x,y);
    System.out.println(k);
    s[++top]=k; --here is my problem
    }//getPairs

    I tried making as few changes to your code as possible, but your idea should basically work. Potential problems:
    1. Doesn't allow for more input than 1 pair.
    2. By storing pair in an array, you must know the exact size of the array you will need beforehand. You might be better off storing the Pair(s) in a Vector and then converting that to an array.
    3.Your exception handlers need some work. Basically, your exception handlers put out a message or do nothing and then you continue processing. Not good.
    4. No cleanup of file resources after you have completed
    import java.io.*;
    public class PairList{
         private Pair s[];
         private int top;
         public PairList(int x){
              top = -1;
              s = new Pair[x];
         }//constructor
         public void getPairs()throws Exception{
              BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
              String a = null, b = null;
              try{
                   a=input.readLine();
                   b=input.readLine();
              }//try
              catch(IOException e){
                   System.out.println("Can't read input");
              }//catch
              int x=0;
              int y=0;
              try{
                   x=Integer.parseInt(a);
              }//try
              catch(NumberFormatException e){
              try{
                   y=Integer.parseInt(b);}//try
              catch(NumberFormatException e){
              Pair k=new Pair(x,y);
              System.out.println(k.toString());
              s[++top]=k; //here is my problem
         }//getPairs
    class Pair {
         private int xx;
         private int yy;
         public Pair(int x, int y) {
              xx = x;
              yy = y;
         public String toString() {
              return("X = " + xx + "  Y = " + yy);
    }

  • Write an object that has array

    I am trying to figure out how to write a object with an array
    Player[] jim = new Player[30];
    for (int i=0;i<30;i++)
    jim= new Player("" + i);
    I am trying to figure out how to get the number of points jim scores in a month, so i need 31 days and a way to input the number of points he scored. Any help would be great

    Well, i think you don't have to create a whole bunch of arrays to enter jim's scores in 31 days. I presume you already have a separate object called Player. Why not set a List attribute on that object and manipulate the scores there. You don't need to instantiate an array for that.
    public class Player{
        private List scores = null;
        ....... //other attributes here
        public Player(){
            scores = new ArrayList();
        public void addScore(String score){
            scores.add(score);
        public List getScore(){
            return scores;
    }well, of course to get the contained items from the List, do manipulate it using arrays. And well, just parse down the returned scores to int because they are stored as strings here.
    hope that helps.

  • Problems launching Object Manager and Array Manager in SSGD 4.20.983

    Hi,
    I have just installed SSGD 4.20.983 in a server which is running Solaris 10. The language of this server is Spanish.
    When I access to the webtop, I 'm not be able to launch the applications Object Manager and Array Manager.
    When I try to launch them, in the details box appears "Contrase�a" and them the timeout expires. Contrase�a is the same that password in Spanish.
    Anyone can help me?
    Regards,
    Diego

    Do you have any logfiles which look like : execpePID_error.log?
    These files should contain more information.
    Also take a look at the following section of the Administration Guide: [http://docs.sun.com/source/820-6689/chapter4.html#d0e21816]
    Especially the part '+Increasing the Log Output+'
    - Remold

  • How to access child movieclip info of an object in an array?

    Hi
    I've dynamically created a whole bunch of movieclips.
    I've given each clip a name based on a variable number:
         mc.name = "mc"+i;
    I've also use addChild to add a couple of dynamic text fields to each movieClip, named myText1 and myText2.
    I then push each movieClip object into an array:
         myArray.push(mc);
    When I addChild the movieClips, they display fine, complete with each textField.  And if I use the following loop to trace the name of each clip in the array, I get:
         for(var i=0; i<myArray.length; i++)
                   trace(myArray[i].name);
    output:
         mc1
         mc2
         mc3
         mc4
    etc
    What I want to now is be able to access the text fields within each movieclip in the array.  However, I am getting errors when I try different ways.  For example:
         for(var i=0; i<myArray.length; i++)
                   trace(myArray[i].myText1.text);
    gives the error: A term is undefined and has no properties.
    How do you access the values and contents of the children of movieClip objects that are stored in arrays?
    Thanks
    Shaun

    For whatever reason, dynamically added children cannot be targeted that way.  If you added the textfields dynamically you may need to use getChildByName() to target them.  It partly depends on how you created them and whether or not you have direct access to them.  Aside from that you could also assign the textfields to variables that you create for the mc and target those by their variable names.
    The following demos these two approaches:
    var mc:MovieClip = new MovieClip();
    addChild(mc);
    var tf:TextField = new TextField();
    tf.text = "this is text";
    mc.addChild(tf);
    // first way
    tf.name = "tfield";
    trace(TextField(mc.getChildByName("tfield")).text);
    // second way
    mc.tfid = tf;
    trace(mc.tfid.text);
    You could also store the textfields in arrays as they are created and have direct access to them with out the need to target the mc... the index should be the same as that which you use for the mc anyways.

  • Problem using Oracle Object Types and Arrays.

    I'm currently trying to work with oracle object types in java and I'm running into some issues when trying to add an item to an array.
    The basic idea is that I have a header object and a detail object (both only containing an ID and a description). Inside of my java code I'm trying to add a new detail line to the header that has been retrieved from the database.
    Here's what I'm working with.
    --Oracle Objects:
    CREATE OR REPLACE TYPE dtl_obj AS OBJECT
        detail_id INTEGER,
        header_id INTEGER,
        detail_desc VARCHAR2(300)
    CREATE TYPE dtl_tab AS TABLE OF dtl_obj;
    CREATE OR REPLACE TYPE hdr_obj AS OBJECT
        header_id INTEGER,
        src VARCHAR(30),
        details dtl_tab
    CREATE TYPE hdr_tab AS TABLE OF hdr_obj;
    /--Java test methods
         public static void main(String[] args) throws SQLException,
                   ClassNotFoundException
              // Initialize the objects
              Test t = new Test();
              t.connect(); //Connects to the database
              //The oracle connection will be accessible through t.conn
              // Create the oracle call
              String query = "{? = call get_header(?)}";
              OracleCallableStatement cs = (OracleCallableStatement) t.conn.prepareCall(query);
              cs.registerOutParameter(1, OracleTypes.ARRAY, "HDR_TAB"); //Register the out parameter and associate it with our oracle type
              int[] hdrs = { 240 }; //we just want one for testing.
              ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor(
                        "ARRAY_T", t.conn);
              oracle.sql.ARRAY oHdrs = new ARRAY(descriptor, t.conn, hdrs);
              cs.setARRAY(2, oHdrs); //Set the headers to retrieve
              // Execute the query
              cs.executeQuery();
              try
                   ARRAY invArray = cs.getARRAY(1);
                   // Start the retrieval process
                   Class cls = Class.forName(Header.class.getName());
                   Map<String, Class<?>> map = t.conn.getTypeMap();
                   map.put(Header._SQL_NAME, cls);
                   Object[] invoices = (Object[]) invArray.getArray();
                   ArrayList<Header> invs = new ArrayList(
                             java.util.Arrays.asList(invoices));
                   if (invs != null)
                        for (Header inv : invs)
                             System.out.println(inv.getHeaderId() + " " + inv.getSrc());
                             t.addDetail(inv, "new line");
                             for (Detail dtl : inv.getDetails().getArray()) // Exception thrown here
    //                              java.sql.SQLException: Fail to construct descriptor: Invalid arguments
    //                              at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
    //                              at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:162)
    //                              at oracle.jdbc.driver.DatabaseError.check_error(DatabaseError.java:861)
    //                              at oracle.sql.StructDescriptor.createDescriptor(StructDescriptor.java:128)
    //                              at oracle.jpub.runtime.MutableStruct.toDatum(MutableStruct.java:109)
    //                              at com.pcr.tst.Detail.toDatum(Detail.java:40)
    //                              at oracle.jpub.runtime.Util._convertToOracle(Util.java:151)
    //                              at oracle.jpub.runtime.Util.convertToOracle(Util.java:138)
    //                              at oracle.jpub.runtime.MutableArray.getDatumElement(MutableArray.java:1102)
    //                              at oracle.jpub.runtime.MutableArray.getOracleArray(MutableArray.java:550)
    //                              at oracle.jpub.runtime.MutableArray.getObjectArray(MutableArray.java:689)
    //                              at oracle.jpub.runtime.MutableArray.getObjectArray(MutableArray.java:695)
    //                              at com.pcr.tst.DetailTable.getArray(DetailTable.java:76)
    //                              at com.pcr.tst.Test.main(Test.java:91)
                                  System.out.println(dtl.getDetailDesc());
              catch (Exception ex)
                   System.out.println("Error while retreiving header");
                   ex.printStackTrace();
              public void addDetail(Header hdr, String desc) throws Exception
              if (hdr == null)
                   throw new Exception("header not initialized");
              // Convert the current list to an ArrayList so we can easily add to it.
              ArrayList<Detail> dtlLst = new ArrayList<Detail>();
              dtlLst.addAll(java.util.Arrays.asList(hdr.getDetails().getArray()));
              // Create the new detail
              Detail dtl = new Detail();
              dtl.setDetailDesc(desc);
              // add the new detail
              dtlLst.add(dtl);
              Detail[] ies = new Detail[dtlLst.size()];
              ies = dtlLst.toArray(new Detail[0]);
              DetailTable iet = new DetailTable(ies);
              hdr.setDetails(iet);
         }I know its the addDetail method causing the issue because if I comment out the t.addDetail(inv, "new line"); call it works fine.
    Message was edited by:
    pcristini

    Oracle® Database Object-Relational Developer's Guide
    Also note that object relational database design is often less performant and scalable than relational. It is not very often used in production environments.
    However, the object orientated programming feature that is provided with Oracle object feature set are used and can make development and interfaces a lot easier.
    So in a nutshell. Say no to ref and nested table columns. Say yes to most of the other object features. IMO of course...

  • How can i convert object to byte array very*100 fast?

    i need to transfer a object by datagram packet in embeded system.
    i make a code fallowing sequence.
    1) convert object to byte array ( i append object attribute to byte[] sequencailly )
    2) send the byte array by datagram packet ( by JNI )
    but, it's not satisfied my requirement.
    it must be finished in 1ms.
    but, converting is spending 2ms.
    network speed is not bottleneck. ( transfer time is 0.3ms and packet size is 4096 bytes )
    Using ObjectOutputStream is very slow, so i'm using this way.
    is there antoher way? or how can i improve?
    Edited by: JongpilKim on May 17, 2009 10:48 PM
    Edited by: JongpilKim on May 17, 2009 10:51 PM
    Edited by: JongpilKim on May 17, 2009 10:53 PM

    thanks a lot for your reply.
    now, i use udp socket for communication, but, i must use hardware pci communication later.
    so, i wrap the communication logic to use jni.
    for convert a object to byte array,
    i used ObjectInputStream before, but it was so slow.
    so, i change the implementation to use byte array directly, like ByteBuffer.
    ex)
    public class ByteArrayHelper {
    private byte[] buf = new byte[1024];
    int idx = 0;
    public void putInt(int val){
    buf[idx++] = (byte)(val & 0xff);
    buf[idx++] = (byte)((val>>8) & 0xff);
    buf[idx++] = (byte)((val>>16) & 0xff);
    buf[idx++] = (byte)((val>>24) & 0xff);
    public void putDouble(double val){ .... }
    public void putFloat(float val){ ... }
    public byte[] toByteArray(){ return this.buf; }
    public class PacketData {
    priavte int a;
    private int b;
    public byte[] getByteArray(){
    ByteArrayHelper helper = new ByteArrayHelper();
    helper.putInt(a);
    helper.putInt(b);
    return helper.toByteArray();
    but, it's not enough.
    is there another way to send a object data?
    in java language, i can't access memory directly.
    in c language, if i use struct, i can send struct data to copy memory by socket and it's very fast.
    Edited by: JongpilKim on May 18, 2009 5:26 PM

  • Not possible to store multiple fileReference object in same array?

    Hi all,
    I'm trying to store multiple fileReference  object in one array. But everytime I push() in a new object the old  objects that's already in the array gets set to the latest object.
    I'm  letting the user select an image. Then I push the selected  fileReference object into an array like my_array.push(  FileReference(event.target) );
    If I then run a loop on  "my_array" to check it's content I'm getting the latest pushed  fileReference object for every index in the array.
    With one object pushed in:
    1. Image1.jpg
    With two objects pushed in:
    1. Image2.jpg
    2. Image2.jpg
    Anyone have any thoughts on this?
    Thank you so much

    This is basically what I'm doing. The code is cut out from a larger portion so there might be errors, but hopefully not.
    // Local Files
    private var localFiles:FileReference           = new FileReference();
    private var fileList:Array                = new Array();
    private function browse(event:MouseEvent)
         trace("[Browse] Using local files");
         localFiles.addEventListener(Event.SELECT, onLocalFilesSelected);
         localFiles.browse(getAllowedTypes());
    * LOCAL FILE
    private function onLocalFilesSelected(e:Event)
         localFiles.addEventListener(Event.COMPLETE, localFileHandler);
         localFiles.load();
    private function localFileHandler(event:Event):void
         localFiles.removeEventListener(Event.COMPLETE, localFileHandler);
         fileList.push(FileReference(event.target));
         showFileList();
    private function showFileList():void
         for(var $x:int=0;$x<fileList.length;$x++)
              var file:FileReference = FileReference(fileList[$x]);
              trace($x+": " + file.name);
    Thank you

  • Possible bug when creating multiple detail view objects

    using jdev 11.1.1.0.0 to build jsf/adf applications. I wanted to report what seems like a bug in 11g. I have a parent table which has two child tables. After creating the appropriate entities, associations, views, and view links, the app module looks like this:
    MasterView
    --DetailView1
    --DetailView2
    The two detail view objects are on the same level, they are both direct children of the Master view.
    Here's what's happening:
    1) I create the master entity/view objects (MasterView)
    2) I create one of the detail entity/view objects (DetailView1).
    3) I create the association and view link to establish relationship between MasterView and DetailView1. Everything works fine.
    4) I create the entity/view objects for second detail view (DetailView2)
    5) When I attempt to create a second view link (based off an association) to establish the relationship between MasterView and DetailView2, the query clauses of the Create View Link wizard (screens 4 and 5) do not get created properly. I finish the wizard and save. Not only does this view link not get created properly, but in the process the query clauses that were defined in the first view link between MasterView and DetailView1 are wiped out. This will break any coordination between master and detail views in both the app module tester and runtime. Has anyone seen this problem?

    fyi, it looks like this issue has been resolved with jdev 11.1.1.0.2 (Update 2)

  • Querying the data type of objects in an Array?

    I'm able to determine that an argument is an Array using the following query:
    SELECT DATA_TYPE
    FROM all_arguments
    WHERE OBJECT_NAME = 'MY_PROCEDURE' AND ARGUMENT_NAME = 'MY_ARRAY_PARAM'
    DATA_TYPE will be 'PL/SQL TABLE' if the argument/parameter is an array.
    My question is: Is there a way to query what the type of the objects in the array should be? Like NVARCHAR2, VARCHAR2, RAW, DECIMAL, etc.
    Any help is very appreciated!

    I guess the part I'm having trouble with is when the
    Array is defined in a package because the type
    doesn't get listed in "all_coll_types". well, the workaround here would be - the parsing of PACKAGE text - and finding your needed type of array:
    SQL> create or replace package TEST_PACK as
      2          TYPE test_type is table of varchar2(100);
      3   end test_pack;
      4  /
    Package created
    SQL>
    SQL> create or replace package body TEST_PACK as
      2    vc_array test_type;
      3    begin
      4     null;
      5    end;
      6  /
    Package body created
    SQL>
    SQL> select * from user_source t
      2   where name = 'TEST_PACK'
      3  /
    NAME                           TYPE               LINE TEXT
    TEST_PACK                      PACKAGE               1 package TEST_PACK as
    TEST_PACK                      PACKAGE               2         TYPE test_type is table of varchar2(100);
    TEST_PACK                      PACKAGE               3  end test_pack;
    TEST_PACK                      PACKAGE BODY          1 package body TEST_PACK as
    TEST_PACK                      PACKAGE BODY          2   vc_array test_type;
    TEST_PACK                      PACKAGE BODY          3   begin
    TEST_PACK                      PACKAGE BODY          4    null;
    TEST_PACK                      PACKAGE BODY          5   end;
    8 rows selected
    SQL>

  • Objects in an Array

    I'm having trouble getting my objects into an array. The program compilies just fine, but when you run it, it just outputs all null values.
    //import necessary classes
    import java.util.Scanner;
    import java.io.File;
    import java.io.IOException;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import javax.swing.JOptionPane;
    public class DanMPA6
      public DanMPA6() throws IOException
      // get the name of the input file from the username
      String inFile = JOptionPane.showInputDialog( "Enter the name of the file:" ) ; 
      File inputFile = new File(inFile);
      Scanner scan = new Scanner(inputFile);
      scan.useDelimiter("[|\n\r]+");
    // Passenger myPassObj;
      Passenger[] ayPass = new Passenger [1500];
      int count = 0;
      //start the loop
      while (scan.hasNext())
                  // read all of the information from the data file in order
                   int fakeID = Integer.parseInt(scan.next());
                 String fakeClass = scan.next();
                   int fakeSurvive = Integer.parseInt(scan.next());
                 String fakeName = scan.next();
               double fakeAge = Double.parseDouble(scan.next()); 
               String fakeFrom = scan.next();
                   String fakeTo = scan.next();
                   String fakeRoom = scan.next();
                 String fakeTicket = scan.next();
                 String fakeLifeboat = scan.next();     
                 String fakeSex = scan.next();
                 Passenger myPassObj = new Passenger (fakeID, fakeClass, fakeSurvive, fakeName, fakeAge, fakeFrom, fakeTo, fakeRoom, fakeTicket, fakeLifeboat, fakeSex);
                   ayPass[count] = myPassObj;
                   count++;
           /*  String outFile = JOptionPane.showInputDialog (null, "Give the name of the output file:");
               FileWriter fw = new FileWriter (outFile, false);
               BufferedWriter bw = new BufferedWriter(fw);
               bw.write(ayPass[count] + "\n"); */
    public static void main (String [] args) throws IOException
         new DanMPA6();                      
    class Passenger
    // data members
           int passID;
           String passClass;
           int passSurvive;
           String passName;
           double passAge;
           String passFrom;
           String passTo;
           String passRoom;
           String passTicket;
           String passLifeboat;     
           String passSex;
           public Passenger (int fakeID, String fakeClass, int fakeSurvive, String fakeName, double fakeAge, String fakeFrom, String fakeTo, String fakeRoom,  String fakeTicket,  String fakeLifeboat, String fakeSex)
           passID = fakeID;
           passClass = fakeClass;
           passSurvive = fakeSurvive;
           passName = fakeName;
           passAge = fakeAge;
           passFrom = fakeFrom;
           passTo = fakeTo;
           passRoom = fakeRoom;
           passTicket = fakeTicket;
           passLifeboat = fakeLifeboat;     
           passSex = fakeSex;
         

    Thank you very much! That worked. So now I have all my objects in the array, but it seems that I'm running into a different problem when I attempt to output the results into a different .txt file. It creates the file, but with nothing in it! I even tried just a basic line of text and that didn't work either.
    This is the code that I was attempting to do that with:
    FileWriter fw = new FileWriter (outFile, false);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(ayPass[count] + "\n");

  • Converting object wrapper type array into equivalent primary type array

    Hi All!
    My question is how to convert object wrapper type array into equivalent prime type array, e.g. Integer[] -> int[] or Float[] -> float[] etc.
    Is sound like a trivial task however the problem is that I do not know the type I work with. To understand what I mean, please read the following code -
    //Method signature
    Object createArray( Class clazz, String value ) throws Exception;
    //and usage should be as follows:
    Object arr = createArray( Integer.class, "2%%3%%4" );
    //"arr" will be passed as a parameter of a method again via reflection
    public void compute( Object... args ) {
        a = (int[])args[0];
    //or
    Object arr = createArray( Double.class, "2%%3%%4" );
    public void compute( Object... args ) {
        b = (double[])args[0];
    //and the method implementation -
    Object createArray( Class clazz, String value ) throws Exception {
         String[] split = value.split( "%%" );
         //create array, e.g. Integer[] or Double[] etc.
         Object[] o = (Object[])Array.newInstance( clazz, split.length );
         //fill the array with parsed values, on parse error exception will be thrown
         for (int i = 0; i < split.length; i++) {
              Method meth = clazz.getMethod( "valueOf", new Class[]{ String.class });
              o[i] = meth.invoke( null, new Object[]{ split[i] });
         //here convert Object[] to Object of type int[] or double[] etc...
         /* and return that object*/
         //NB!!! I want to avoid the following code:
         if( o instanceof Integer[] ) {
              int[] ar = new int[o.length];
              for (int i = 0; i < o.length; i++) {
                   ar[i] = (Integer)o;
              return ar;
         } else if( o instanceof Double[] ) {
         //...repeat "else if" for all primary types... :(
         return null;
    Unfortunately I was unable to find any useful method in Java API (I work with 1.5).
    Did I make myself clear? :)
    Thanks in advance,
    Pavel Grigorenko

    I think I've found the answer myself ;-)
    Never thought I could use something like int.class or double.class,
    so the next statement holds int[] q = (int[])Array.newInstance( int.class, 2 );
    and the easy solution is the following -
    Object primeArray = Array.newInstance( token.getPrimeClass(), split.length );
    for (int j = 0; j < split.length; j++) {
         Method meth = clazz.getMethod( "valueOf", new Class[]{ String.class });
         Object val = meth.invoke( null, new Object[]{ split[j] });
         Array.set( primeArray, j, val );
    }where "token.getPrimeClass()" return appropriate Class, i.e. int.class, float.class etc.

  • Problem occured when create a tree table for master-detail view objects using SQL queries?

    I am programming a tree table for master-detail view objects using SQL queries and these 2 view objects are not simple singel tables queries, and 2 complex SQL are prepared for master and view objects. see below:
    1. Master View object (key attribute is SourceBlock and some varaible bindings are used for this view object.)
    SELECT  cntr_list.SOURCE_BLOCK,                   
            sum(                   
             case when cntr_list.cntr_size_q = '20'                   
                  then cntr_list.cntr_qty                   
                  else 0 end ) as cntr20 ,                   
            sum(                   
             case when cntr_list.cntr_size_q = '40'                   
                  then cntr_list.cntr_qty                   
                  else 0 end ) as cntr40 ,                   
             sum(                   
             case when cntr_list.cntr_size_q = '45'                   
                  then cntr_list.cntr_qty                   
                  else 0 end ) as cntr45                    
    FROM (       
        SELECT yb1.BLOCK_M as SOURCE_BLOCK,       
               scn.CNTR_SIZE_Q,        
               count(scn.CNTR_SIZE_Q) AS cntr_qty        
        FROM  SHIFT_CMR scm, SHIFT_CNTR scn, YARD_BLOCK yb1, YARD_BLOCK yb2       
        WHERE       
        scm.cmr_n = scn.cmr_n             
        AND (scm.plan_start_dt BETWEEN to_date(:DateFrom,'YYYY/MM/DD HH24:MI:SS') AND to_date(:DateTo,'YYYY/MM/DD HH24:MI:SS')                 
        OR scm.plan_end_dt BETWEEN to_date(:DateFrom,'YYYY/MM/DD HH24:MI:SS') AND to_date(:DateTo,'YYYY/MM/DD HH24:MI:SS'))                 
        AND scm.shift_mode_c = :ShiftModeCode                           
        AND scm.end_terminal_c = :TerminalCode      
        AND scm.start_terminal_c = yb1.terminal_c                  
        AND scm.start_block_n = yb1.block_n                  
        AND substr(scn.start_location_c,(instr(scn.start_location_c,',',1,5)+1),instr(scn.start_location_c,',',1,6)-(instr(scn.start_location_c,',',1,5)+1)) BETWEEN yb1.slot_from_n AND yb1.slot_to_n                  
        AND scm.end_terminal_c = yb2.terminal_c                  
        AND scm.end_block_n = yb2.block_n                  
        AND substr(scn.end_location_c,(instr(scn.end_location_c,',',1,5)+1),instr(scn.end_location_c,',',1,6)-(instr(scn.end_location_c,',',1,5)+1)) BETWEEN yb2.slot_from_n AND yb2.slot_to_n           
        AND scn.status_c not in (1, 11)             
        AND scn.shift_type_c = 'V'             
        AND scn.source_c = 'S'       
        GROUP BY yb1.BLOCK_M, scn.CNTR_SIZE_Q       
    ) cntr_list       
    GROUP BY cntr_list.SOURCE_BLOCK
    2. Detail View object (key attributes are SourceBlock and EndBlock and same varaible bindings are used for this view object.)
    SELECT  cntr_list.SOURCE_BLOCK, cntr_list.END_BLOCK,                
            sum(                     
             case when cntr_list.cntr_size_q = '20'                     
                  then cntr_list.cntr_qty                     
                  else 0 end ) as cntr20 ,                     
            sum(                     
             case when cntr_list.cntr_size_q = '40'                     
                  then cntr_list.cntr_qty                     
                  else 0 end ) as cntr40 ,                     
             sum(                     
             case when cntr_list.cntr_size_q = '45'                     
                  then cntr_list.cntr_qty                     
                  else 0 end ) as cntr45                      
    FROM (         
        SELECT yb1.BLOCK_M as SOURCE_BLOCK,     
               yb2.BLOCK_M as END_BLOCK,  
               scn.CNTR_SIZE_Q,          
               count(scn.CNTR_SIZE_Q) AS cntr_qty          
        FROM  SHIFT_CMR scm, SHIFT_CNTR scn, YARD_BLOCK yb1, YARD_BLOCK yb2         
        WHERE         
        scm.cmr_n = scn.cmr_n               
        AND (scm.plan_start_dt BETWEEN to_date(:DateFrom,'YYYY/MM/DD HH24:MI:SS') AND to_date(:DateTo,'YYYY/MM/DD HH24:MI:SS')                   
        OR scm.plan_end_dt BETWEEN to_date(:DateFrom,'YYYY/MM/DD HH24:MI:SS') AND to_date(:DateTo,'YYYY/MM/DD HH24:MI:SS'))                   
        AND scm.shift_mode_c = :ShiftModeCode                             
        AND scm.end_terminal_c = :TerminalCode        
        AND scm.start_terminal_c = yb1.terminal_c                    
        AND scm.start_block_n = yb1.block_n                    
        AND substr(scn.start_location_c,(instr(scn.start_location_c,',',1,5)+1),instr(scn.start_location_c,',',1,6)-(instr(scn.start_location_c,',',1,5)+1)) BETWEEN yb1.slot_from_n AND yb1.slot_to_n                    
        AND scm.end_terminal_c = yb2.terminal_c                    
        AND scm.end_block_n = yb2.block_n                    
        AND substr(scn.end_location_c,(instr(scn.end_location_c,',',1,5)+1),instr(scn.end_location_c,',',1,6)-(instr(scn.end_location_c,',',1,5)+1)) BETWEEN yb2.slot_from_n AND yb2.slot_to_n             
        AND scn.status_c not in (1, 11)               
        AND scn.shift_type_c = 'V'               
        AND scn.source_c = 'S'         
        GROUP BY yb1.BLOCK_M, yb2.BLOCK_M, scn.CNTR_SIZE_Q         
    ) cntr_list         
    GROUP BY cntr_list.SOURCE_BLOCK, cntr_list.END_BLOCK
    3. I create a view link to create master-detail relationship for these 2 view objects.
    masterview.SourceBlock (1)->detailview.SourceBlock (*).
    4. I create a tree table using these 2 view objects with master-detail relationship.
    When I set default value for variable bindings of these 2 view objects and the matching records exist, tree table can work well. I can expand the master row to display detail row in UI.
    But I need to pass in dymamic parameter value for variable bindings of these 2 view objects, tree table cannnot work again. when I expand the master row and no detail row are displayed in UI.
    I am sure that I pass in correct parameter value for master/detail view objects and matching records exist.
    Managed Bean:
            DCIteratorBinding dc = (DCIteratorBinding)evaluteEL("#{bindings.MasterView1Iterator}");
            ViewObject vo = dc.getViewObject();
            System.out.println("Before MasterView1Iterator vo.getEstimatedRowCount()="+ vo.getEstimatedRowCount());
            System.out.println("Before MasterView1Iterator ShiftModeCode="+ vo.ensureVariableManager().getVariableValue("ShiftModeCode"));
            vo.ensureVariableManager().setVariableValue("DateFrom", dateFrom);
            vo.ensureVariableManager().setVariableValue("DateTo", dateTo);
            vo.ensureVariableManager().setVariableValue("ShiftModeCode", shiftModeC);
            vo.ensureVariableManager().setVariableValue("TerminalCode", terminalCode);
            vo.executeQuery();
            System.out.println("MasterView1Iterator vo.getEstimatedRowCount()="+ vo.getEstimatedRowCount());
            DCIteratorBinding dc1 = (DCIteratorBinding)evaluteEL("#{bindings.DetailView1Iterator}");
            ViewObject vo1 = dc1.getViewObject();
            System.out.println("Before DetailView1Iterator vo1.getEstimatedRowCount()="+ vo1.getEstimatedRowCount());
            System.out.println("Before DetailView1Iterator ShiftModeCode="+ vo1.ensureVariableManager().getVariableValue("ShiftModeCode"));
            vo1.ensureVariableManager().setVariableValue("DateFrom", dateFrom);
            vo1.ensureVariableManager().setVariableValue("DateTo", dateTo);
            vo1.ensureVariableManager().setVariableValue("ShiftModeCode", shiftModeC);
            vo1.ensureVariableManager().setVariableValue("TerminalCode", terminalCode);
            vo1.executeQuery();
            System.out.println("after DetailView1Iterator vo1.getEstimatedRowCount()="+ vo1.getEstimatedRowCount());
    5.  What's wrong in my implementation?  I don't have no problem to implement such a tree table if using simple master-detail tables view object, but now I have to use such 2 view objects using complex SQL for my requirement and variable bindings are necessary for detail view object although I also think a bit strange by myself.

    Hi Frank,
    Thank you and it can work.
    public void setLowHighSalaryRangeForDetailEmployeesAccessorViewObject(Number lowSalary,
                                                                              Number highSalary) {
            Row r = getCurrentRow();
            if (r != null) {
                RowSet rs = (RowSet)r.getAttribute("EmpView");
                if (rs != null) {
                    ViewObject accessorVO = rs.getViewObject();
                    accessorVO.setNamedWhereClauseParam("LowSalary", lowSalary);
                    accessorVO.setNamedWhereClauseParam("HighSalary", highSalary);
                executeQuery();
    but I have a quesiton in this way. in code snippet, it is first getting current row of current master VO to determine if update variables value of detail VO. in my case, current row is possibly null after executeQuery() of master VO and  I have to change current row manually like below.
    any idea?
                DCIteratorBinding dc = (DCIteratorBinding)ADFUtil.evaluateEL("#{bindings.SSForecastSourceBlockView1Iterator}");
                ViewObject vo = dc.getViewObject();           
                vo.ensureVariableManager().setVariableValue("DateFrom", dateFrom);
                vo.ensureVariableManager().setVariableValue("DateTo", dateTo);
                vo.ensureVariableManager().setVariableValue("ShiftModeCode", shiftModeC);
                vo.ensureVariableManager().setVariableValue("TerminalCode", terminalCode);
                vo.executeQuery();
                vo.setCurrentRowAtRangeIndex(0);
                ((SSForecastSourceBlockViewImpl)vo).synchornizeAccessorVOVariableValues();

  • Object tables/associative arrays are using lots of memory what is alternate

    I'm using mostly object tables/associative arrays in my package and it is using lots of server memorey so i want to use a different technicque to save momorey .
    like using create global temporary table or nested Table Store as or creating table run time at the start and droping it in the end .
    do have any suggestion for this ?
    for this package i'm retriving data from different table into object tables and do calculation in memorey before i send data to front end for reporting using reference cursor .
    give me your suggetion or if you know any example code for this type of process using different technique please let us know .
    thank you very much
    regards
    shailen Patel

    You can create a global temporary table like this:
    CREATE GLOBAL TEMPORARY TABLE AR_TRIAL_RCPT(
      LOC_ACCT_ID NUMBER(12),  
      ACCT_ID NUMBER(12),  
      CURRENCY_ID NUMBER(12),  
      AMT NUMBER(13,   4),  
      AMT_PRIMARY NUMBER(13,   4)
    [ON COMMIT PRESERVE ROWS]
    ;If you want the table truncated on COMMITs leave out the part in brackets other wise leave off the brackets and the table won't be truncated until your session terminates or you explicitly truncate the table.
    You can also define indexes, primary keys, foreign keys, check constraints, etc. on your temporary table if need be to improve processing.
    Now when it comes to inserting into your newly minted global temporary table, you should be able to use one of insert statements from the following anonymous PL/SQL block:
    CREATE GLOBAL TEMPORARY TABLE AR_TRIAL_RCPT(
      LOC_ACCT_ID NUMBER(12),  
      ACCT_ID NUMBER(12),  
      CURRENCY_ID NUMBER(12),  
      AMT NUMBER(13,   4),  
      AMT_PRIMARY NUMBER(13,   4)
    --[ON COMMIT PRESERVE ROWS]
    CREATE GLOBAL succeeded.
    declare
    l_open_receipt_select_1 varchar2(4000) :=
        'select 1, 1, 1, 12.05, 12.05 from dual';
    l_open_receipt_select_2 varchar2(4000) :=
        'select 2, 2, 1, 17.05, 17.05 from dual';
    l_open_receipt_select_3 varchar2(4000) :=
        'select 3 loc_acct_id,
      1 currency_id,
      27.05 amt,
      3 acct_id,
      27.05 amt_primary
      from dual';
    l_open_receipt_select_4 varchar2(4000) :=
        'select 4 loc_acct_id,
      1 currency_id,
      24.35 amt,
      4 acct_id,
      24.35 amt_primary
      from dual';
    l_ins_stmt varchar2(4000);
    begin
      -- If the column order is known ahead of time and is consistent
      -- You can use this form:
      l_ins_stmt :=
        'insert into ar_trial_rcpt (
      loc_acct_id, acct_id, currency_id, amt, amt_primary
      ) '||l_open_receipt_select_1||
      ' union all '||
      l_open_receipt_select_2;
      execute immediate l_ins_stmt;
      -- If the column order is NOT known ahead of time or is INconsistent
      -- You can use this form:
      l_ins_stmt :=
        'insert into ar_trial_rcpt (
      loc_acct_id, acct_id, currency_id, amt, amt_primary
      select loc_acct_id
      , acct_id
      , currency_id
      , amt
      , amt_primary
      from ('||l_open_receipt_select_3||')
      union all
      select loc_acct_id
      , acct_id
      , currency_id
      , amt
      , amt_primary
      from ('||l_open_receipt_select_4||')';
      execute immediate l_ins_stmt;
    end;
    anonymous block completed
    select * from ar_trial_rcpt
    LOC_ACCT_ID ACCT_ID  CURRENCY_ID AMT    AMT_PRIMARY
    1           1        1           12.05  12.05      
    2           2        1           17.05  17.05      
    3           3        1           27.05  27.05      
    4           4        1           24.35  24.35      
    4 rows selected

Maybe you are looking for

  • Is it possible to set a variable in a program from outside before calling

    Suppose I have a program as follows Report Program1.   data: prog1data(10) type c. start-of-selection.   perform Prog1Form. form Prog1Form.   write: prog1data. endform. Now if I have another program which calls the Prog1Form from outside, is there so

  • File to JDBC Sync error

    Hi All, I am doing File to JDBC sync mode. I have configured the scenario while trying to execute i am getting error in JDBC communication chennal. I have create the stucture with help of this link http://help.sap.com/saphelp_nw04/Helpdata/EN/2e/96fd

  • Has anyone had issues with Firefox 13.1 while scrolling web pages

    While scrolling most but not all internet page words get jumpy and blurred. This same thing happened on version 13. I had no problems with 12 or ones before it.

  • Querying from 3 tables

    i want to display the records for this day. the thing is that the data comes from 3 different tables. the query contains the ff columns: date         tableA entryid      tableA audittype   tableA name        tableB shift          tableA package    ta

  • Create iPod or iPhone version generates all white, audio only video

    I have been trying to find any explanation for this by searching here and on Google, with little success. I am trying to export my movies to my ipod with no success. I will explain what I do: I pick a movie from the iTunes Library (it plays just fine