Help! Object Arrays...

Hi,
I'm a novice programmer trying to learn Java. I'm trying to solve a problem in a book I'm learning from - I can use arrays of primitive types with no problem, but I'm having some trouble with arrays of objects. To illustrate what I'm trying to do I'll write a very simple piece of code...I know this is cheesy but it's is only an example:
class Cat
     public String name;
     public int age;
     public static void main( String[] args )
          Cat fluffy = new Cat();
          fluffy.name = "fluffy";
          fluffy.age = 2;          
}In the above example, I've created a class called Cat. It has two fields, 'name' and 'age'. In the main() method I create the object 'fluffy' and set his age to '2'.
That's fine and dandy, but lets say I own more than one cat and I dont want to explicitly create each one like that, so I'll create an array that references objects of the type 'Cat':
class Cat
     public String name;
     public int age;
     public static void main( String[] args )
          Cat[] myPets = new Cat[3];
          myPets[0].name = "fluffy";
          myPets[0].age = 2;
          myPets[1].name = "garfield";
          myPets[1].age = 4;
          myPets[2].name = "heathcliff";
          myPets[2].age = 3;          
}In the main() method I create an array called myPets that references three Cat objects. Afterwards, I try to set the fields of each Cat object in the array (the 'name' and 'age'). This is where I'm having problems...when this code is run it produces a NullPointerException. So my question is...how do I set objects' individual fields when the objects are in an array?

You are having an array of Cats. Which means that the array can act as container for cats, and it contains three fields.
Cat pets[] = new Cat[3];
What you need to do now, is to put cats into the container. Only if there are cats in there, you can give those cats name. This means :
//make a new cat
Cat cat1 = new Cat();
// put cat into array
pets[0] = cat1;
// name cat within the array
pets[0].name = "Garfield";
pets[0].age = 3;
Hope this helps,
rh

Similar Messages

  • I need help with a Object Array

    I am having trouble and this maybe really simple seeing that I am fairly new to java but I have text that is being broken down in to preset part with those parts stored in Object arrays.
    Now I also have a object array inside my object array. Within the second object array are the broken down parts of the text and I want to compare this text with another string so for example this is what I am trying
    boolean found = false;
    for (int i = 0; i < FirstObjectArray.length ;i++)
         Object[] SecondObjectArray = (Object[]) FirstObjectArray;
         if(SecondObjectArray[0] == "string")
              found = true;
              break;
         else
              found = false;
    }Help would be very appreciated.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    astlanda wrote:
    Sure, you're right.
    [public boolean equals(Object obj)|http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#equals%28java.lang.Object%29]
    sharkura said all the OP needs at the moment. I just wanted to clarify a bit why You don't use == 99.999% of the time with objects, and never with String.
    I have argued elsewhere in these forums that it is inappropriate to tell anyone that you never use == to compare objects. This has not always been accepted. I have, on rare occasions, known experienced developers to blindly compare two objects with equals(), and cite the professor that taught them, 15 years iin the past, that object references are never compared using ==, but always with equals().
    However, the cases where == is appropriate and equals() is not are indeed rare, but not, in my experience, non-existent. In my statement, I probably exaggerated. And String is a case where I can probably accept that you will probably never go wrong with equals(). If the String has been pooled (see String::intern()), you can actually use either. From the javadocs: "*It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.*"
    ¦ {Þ                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Java Null Pointer Exception when assigning a value to an Object Array

    I am working on a webservice where the request can contain a dynamic array of SingleOwnerRequestNodeDetail objects. I need to read these objects in and sort them according to an orderNbr that is contained in the object.
    I am attempting to read these object into a Comparable class and sort them. I am having problems when I try to insert the objects into my object array ComparableBO[]. I get the following error: Exception during processing: java.lang.NullPointerException
    Any assistance would be greatly appreciated.
    Here's my class:
    public class ComparatorBO  implements Comparable {
         private SingleOwnerRequestNodeDetail nodeDetailInfo;
         private int orderNbr;
         public SingleOwnerRequestNodeDetail getNodeDetailInfo() {
              return nodeDetailInfo;
         public void setNodeDetailInfo(SingleOwnerRequestNodeDetail nodeDetailInfo) {
              this.nodeDetailInfo = nodeDetailInfo;
         public int getOrderNbr() {
              return Integer.parseInt(nodeDetailInfo.getSingleOwnerRequestOrderNbr());
         public void setOrderNbr (int orderNbr) {
              this.orderNbr = orderNbr;
         public int compareTo(Object anotherNodeDetailInfo)throws ClassCastException {
              if (!(anotherNodeDetailInfo instanceof ComparatorBO))
                   throw new ClassCastException ("An single owner request node detail object is expected");
              int anotherNodeDetailOrderNbr = ((ComparatorBO)anotherNodeDetailInfo).getOrderNbr();
              return this.orderNbr - anotherNodeDetailOrderNbr;
    }Here's the code where I read in the objects and attempt to place them in the comparableBO[]
    ComparatorBO[] comparatorBOArray = null;
    comparatorBOArray = new ComparatorBO[requestInfo.length];
              for (int i=0; i < requestInfo.length; i++)
                   SingleOwnerRequestNodeDetail nodes = new SingleOwnerRequestNodeDetail();
                   ComparatorBO comparatorBO = new ComparatorBO();
                   nodes.setSingleOwnerRequestNodeID(requestInfo.getSingleOwnerRequestNodeID());
                   nodes.setSingleOwnerRequestNodeType(requestInfo[i].getSingleOwnerRequestNodeType());
                   nodes.setSingleOwnerRequestOpCode(requestInfo[i].getSingleOwnerRequestOpCode());
                   nodes.setSingleOwnerRequestOrderNbr(requestInfo[i].getSingleOwnerRequestOrderNbr());
                   comparatorBO.setNodeDetailInfo(nodes);                         
                   *comparatorBOArray[i].setNodeDetailInfo(comparatorBO.getNodeDetailInfo());*
                   comparatorBOArray[i].setOrderNbr(Integer.parseInt(nodes.getSingleOwnerRequestOrderNbr()));

    imadeveloper wrote:
    I am working on a webservice where the request can contain a dynamic array of SingleOwnerRequestNodeDetail objects. I need to read these objects in and sort them according to an orderNbr that is contained in the object.
    I am attempting to read these object into a Comparable class and sort them. I am having problems when I try to insert the objects into my object array ComparableBO[]. I get the following error: Exception during processing: java.lang.NullPointerException
    Any assistance would be greatly appreciated.
    Here's my class:
    public class ComparatorBO  implements Comparable {
         private SingleOwnerRequestNodeDetail nodeDetailInfo;
         private int orderNbr;
         public SingleOwnerRequestNodeDetail getNodeDetailInfo() {
              return nodeDetailInfo;
         public void setNodeDetailInfo(SingleOwnerRequestNodeDetail nodeDetailInfo) {
              this.nodeDetailInfo = nodeDetailInfo;
         public int getOrderNbr() {
              return Integer.parseInt(nodeDetailInfo.getSingleOwnerRequestOrderNbr());
         public void setOrderNbr (int orderNbr) {
              this.orderNbr = orderNbr;
         public int compareTo(Object anotherNodeDetailInfo)throws ClassCastException {
              if (!(anotherNodeDetailInfo instanceof ComparatorBO))
                   throw new ClassCastException ("An single owner request node detail object is expected");
              int anotherNodeDetailOrderNbr = ((ComparatorBO)anotherNodeDetailInfo).getOrderNbr();
              return this.orderNbr - anotherNodeDetailOrderNbr;
    }Here's the code where I read in the objects and attempt to place them in the comparableBO[]
    ComparatorBO[] comparatorBOArray = null;
    comparatorBOArray = new ComparatorBO[requestInfo.length];
              for (int i=0; i < requestInfo.length; i++)
                   SingleOwnerRequestNodeDetail nodes = new SingleOwnerRequestNodeDetail();
                   ComparatorBO comparatorBO = new ComparatorBO();
                   nodes.setSingleOwnerRequestNodeID(requestInfo.getSingleOwnerRequestNodeID());
                   nodes.setSingleOwnerRequestNodeType(requestInfo[i].getSingleOwnerRequestNodeType());
                   nodes.setSingleOwnerRequestOpCode(requestInfo[i].getSingleOwnerRequestOpCode());
                   nodes.setSingleOwnerRequestOrderNbr(requestInfo[i].getSingleOwnerRequestOrderNbr());
                   comparatorBO.setNodeDetailInfo(nodes);                         
                   *comparatorBOArray[i].setNodeDetailInfo(comparatorBO.getNodeDetailInfo());*
                   comparatorBOArray[i].setOrderNbr(Integer.parseInt(nodes.getSingleOwnerRequestOrderNbr()));
    Well normally when someone wont tell me what line the error occured in I copy paste their code into my compiler and find out. But you have other classes which you have not shown us so I cannot help you.
    Incase you missed my point, please tell us where the error occured!

  • Object Array problem in Websphere WebServices

    Hi,
    Can someone help me out with a situation that I am stuck with in WebServices.
    I have a WebService which returns a DTO which has a getter and setter for an array of another type of DTO object.
    Sample:-
    public class MyDTO extends AnotherDTO implements Serializable {
    private InnerDTO qcDtoList[] = new InnerDTO[0];
    public MyDTO() {
    public InnerDTO[] getQcDtoList() {
    return qcDtoList;
    public void setQcDtoList(InnerDTO[] resEDXDTOs) {
    qcDtoList = resEDXDTOs;
    But when I generate the WSDL for the webservice using WSAD 5.1 that uses the above DTO, the server side generated skeleton file looks like:-
    public class MyDTO extends AnotherDTO implements java.io.Serializable {
    private InnerDTO[] qcDtoList;
    public MyDTO() {
    public InnerDTO[] getQcDtoList() {
    return qcDtoList;
    public void setQcDtoList(InnerDTO[] qcDtoList) {
    this.qcDtoList = qcDtoList;
    As you can see from above, my initialization info is not available in the generated skeleton. I also tried putting the initialization in the constructor, with no effect.
    What could be the reason for this? And is it possible to initialize my InnerDTO without losing it in the generated skeleton?
    I simply want to initialize the object array.
    If I need to modify my WSDL, what additional annotations should I add on the WSDL to get the desired effect?
    I use WSAD's (Websphere Studio App Developer) IBM Websphere Webservices protocol and the JDK version is 1.3.1 and WSAD version is 5.1.
    I would really appreciate if you can throw light on this?
    Thanx and Regds,
    Prashanth.

    Thank you for the quick response. I looked at the example you suggested and made the following changes. Now I'm receiving an "Invalid datatype" error on the "SELECT column_value FROM TABLE(CAST(tbl_cat AS tbl_integer))" statement. I must be missing something simple and I just can't put my finger on it.
    PROCEDURE SEL_SEARCH_RESULTS (v_term IN VARCHAR2,
    v_categories IN ARCHIVE.integer_aat,
    rs OUT RSType)
    AS
    /* PURPOSE: Return Search Results for the Category and Keyword Provided
    VARIABLES:
    v_categories = Document Categories array entered
    v_term = Keyword entered
    rs = Result Set
    TYPE tbl_integer IS TABLE OF INTEGER;
    tbl_cat tbl_integer;
    BEGIN
    FOR i IN 1 .. v_categories.COUNT
    LOOP
    tbl_cat.EXTEND(1);
    tbl_cat(i) := v_categories(i);
    END LOOP;
    OPEN rs FOR
    SELECT A.ID,
    B.CATEGORY,
    A.FILENAME,
    A.DISPLAY_NAME,
    A.COMMENTS
    FROM TBL_ARCHIVE_DOCUMENTS A,
    TBL_ARCHIVE_DOC_CAT B,
    TBL_ARCHIVE_DOC_KEYWORDS C
    WHERE A.ID = B.ID
    AND A.ID = C.ID
    AND B.CATEGORY IN (SELECT column_value FROM TABLE(CAST(tbl_cat AS tbl_integer)))
    AND C.KEYWORD = v_term
    ORDER BY A.ID;
    END SEL_SEARCH_RESULTS;

  • Need help for array counting

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

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

  • Trouble writing to object array

    Hi I did a semester of java 2 years ago and I'm trying to remember what I knew so please bear with me...
    I am extracting data from an xml file and then writing that information to an object array called files containing 4 string and 1 array. This files array is in turn an element in another object array containing 400 files arrays called records.
    It appeared to be working but when I want it to print out which ever record I have selected it only prints out the last record! It seems to be overwriting each files array with the next?
    Another problem I can only print out an element of the array not the entire thing?
    Please help have spent weeks on this
    Here is the code:
    Object[] Records = new Object[400];
    Object files[] = new Object[5];
    NodeList records = doc.getElementsByTagName("record");
    for( int i = 0; i < records.getLength();i++)
    Element record = (Element) records.item(i);
    NodeList headers = record.getElementsByTagName("header");
    Element header = (Element) headers.item(0);
    NodeList ids = header.getElementsByTagName("identifier");
    for(int j = 0; j < ids.getLength(); j++){
    Element id = (Element) ids.item(j);
    String ID = getText(id);
    files[0] = ID;
    NodeList metadatas = record.getElementsByTagName("metadata");
    Element metadata = (Element) metadatas.item(0);
    NodeList citeseers = metadata.getElementsByTagName("oai_citeseer:oai_citeseer");
    Element citeseer = (Element) citeseers.item(0);
    NodeList titles = citeseer.getElementsByTagName("dc:title");
    for(int k = 0; k < titles.getLength(); k++){
    Element title = (Element) titles.item(k);
    String TITLE = getText(title);
    files[1] = TITLE;
    NodeList subjects = citeseer.getElementsByTagName("dc:subject");
    for(int m = 0; m < subjects.getLength(); m++){
    Element subject = (Element) subjects.item(m);
    String SUBJECT = getText(subject);
    files[2] = SUBJECT;
    NodeList descriptions = citeseer.getElementsByTagName("dc:description");
    for(int n = 0; n < descriptions.getLength(); n++){
    Element description = (Element) descriptions.item(n);
    String DESCRIPTION = getText(description);
    files[3] = DESCRIPTION;
    String[] Names = new String[20];
    NodeList authors = citeseer.getElementsByTagName("oai_citeseer:author");
    for(int l = 0; l < authors.getLength(); l++){
    Element author = (Element) authors.item(l);
    Names[l] = author.getAttribute("name");
    files[4] = Names;
    System.out.println("The id is "+files[0]);
    System.out.println("The title is "+ files[1]);
    System.out.println("The Subject is "+ files[2]);
    System.out.println("The Description is "+ files[3]);
    for(int q=0; q < authors.getLength(); q++){
    System.out.println("The Names are "+ ((String[])files[4])[q]);
    //Records[i] = files;
    System.out.println(((Object[])Records[0])[0]);

    I'm afraid I'm not going to make you a millionaire but I feel so relieved at the moment that if I had a million I'd give it to you!!Yeah, I know you won't make me a millionaire, but I can dream... :)
    thanks for all your helpYou are welcome. Do you understand why you needed to move the creation of the "files" array.

  • How To Load SINGLE CELL Value as Object - In 2D Object Array - InvalidCastException

    Setup: ---- VB.net - Visual Studio 2010 - Excel Version 2010 - Option Strict ON
    The following WORKS FINE all day long for loading MULTIPLE range values IE: ("F2:F5") or more into a 2D Object Array... No problem... as in the following..
    Dim myRangeTwo As Range = ws.Range("F2:F5")  ' MULTIPLE CELL RANGE     
    Dim arr2(,) As Object = CType(myRangeTwo.Value(XlRangeValueDataType.xlRangeValueDefault), Object(,))
    The ws.range("F2:F5") values are stuffed into the myRangeTwo range variable as 2D Objects and then those are easily stuffed into the 2D object array...
    But this does not work for a SINGLE cell range...
    Dim myRangeTwo As Range = ws.Range("F2:F2")    ' SINGLE CELL RANGE F2 ONLY            
    Dim arr2(,) As Object = CType(myRangeTwo.Value(XlRangeValueDataType.xlRangeValueDefault), Object(,))
    This triggers an Invalid Cast Exception error on trying to load into the arr2(,).. because the ws.range("F2:F2") is stuffed into the myRangeTwo variable as a "string"
    not as an object therefore is not possible to stuff it into an Object Array and so correctly causes the Invalid Cast Error...
    How do you handle this seemingly ridiculously simple problem ??
    thanks... Cj

    Hello,
    Simply answer, you need to determine if the range is a single cell or multiple cells. So the following is geared for returning a DataTable for a start and end cell addresses that are different, granted there is no check to see if the cells are valid i.e.
    end cell is before start cell i.e.
    Since B1 and B10 is a valid range we are good but if we pass in F1:F1 or F10:F10 we must make a decision as per the if statement at the start of the function and if I were expecting this to happen I would have another function that returned a single value.
    Option Strict On
    Option Infer On
    Imports Excel = Microsoft.Office.Interop.Excel
    Imports Microsoft.Office
    Imports System.Runtime.InteropServices
    Module ExcelDemoIteratingData_2
    Public Sub DemoGettingDates()
    Dim dt As DataTable = OpenExcelAndIterate(
    IO.Path.Combine(
    AppDomain.CurrentDomain.BaseDirectory,
    "GetDatesFromB.xlsx"),
    "Sheet1",
    "B1",
    "B10")
    Dim SomeDate As Date = #12/1/2013#
    Dim Results =
    From T In dt
    Where Not IsDBNull(T.Item("SomeDate")) AndAlso T.Field(Of Date)("SomeDate") = SomeDate
    Select T
    ).ToList
    If Results.Count > 0 Then
    For Each row As DataRow In Results
    Console.WriteLine("Row [{0}] Value [{1}]",
    row.Field(Of Integer)("Identifier"),
    row.Field(Of Date)("SomeDate").ToShortDateString)
    Next
    End If
    End Sub
    Public Function OpenExcelAndIterate(
    ByVal FileName As String,
    ByVal SheetName As String,
    ByVal StartCell As String,
    ByVal EndCell As String) As DataTable
    If StartCell = EndCell Then
    ' Decide logically what to do or
    ' throw an exception
    End If
    Dim dt As New DataTable
    If IO.File.Exists(FileName) Then
    Dim Proceed As Boolean = False
    Dim xlApp As Excel.Application = Nothing
    Dim xlWorkBooks As Excel.Workbooks = Nothing
    Dim xlWorkBook As Excel.Workbook = Nothing
    Dim xlWorkSheet As Excel.Worksheet = Nothing
    Dim xlWorkSheets As Excel.Sheets = Nothing
    Dim xlCells As Excel.Range = Nothing
    xlApp = New Excel.Application
    xlApp.DisplayAlerts = False
    xlWorkBooks = xlApp.Workbooks
    xlWorkBook = xlWorkBooks.Open(FileName)
    xlApp.Visible = False
    xlWorkSheets = xlWorkBook.Sheets
    ' For/Next finds our sheet
    For x As Integer = 1 To xlWorkSheets.Count
    xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
    If xlWorkSheet.Name = SheetName Then
    Proceed = True
    Exit For
    End If
    Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
    xlWorkSheet = Nothing
    Next
    If Proceed Then
    dt.Columns.AddRange(
    New DataColumn() _
    New DataColumn With {.ColumnName = "Identifier", .DataType = GetType(Int32), .AutoIncrement = True, .AutoIncrementSeed = 1},
    New DataColumn With {.ColumnName = "SomeDate", .DataType = GetType(Date)}
    Dim xlUsedRange = xlWorkSheet.Range(StartCell, EndCell)
    Try
    Dim ExcelArray(,) As Object = CType(xlUsedRange.Value(Excel.XlRangeValueDataType.xlRangeValueDefault), Object(,))
    If ExcelArray IsNot Nothing Then
    ' Get bounds of the array.
    Dim bound0 As Integer = ExcelArray.GetUpperBound(0)
    Dim bound1 As Integer = ExcelArray.GetUpperBound(1)
    For j As Integer = 1 To bound0
    If (ExcelArray(j, 1) IsNot Nothing) Then
    dt.Rows.Add(New Object() {Nothing, ExcelArray(j, 1)})
    Else
    dt.Rows.Add(New Object() {Nothing, Nothing})
    End If
    Next
    End If
    Finally
    ReleaseComObject(xlUsedRange)
    End Try
    Else
    MessageBox.Show(SheetName & " not found.")
    End If
    xlWorkBook.Close()
    xlApp.UserControl = True
    xlApp.Quit()
    ReleaseComObject(xlCells)
    ReleaseComObject(xlWorkSheets)
    ReleaseComObject(xlWorkSheet)
    ReleaseComObject(xlWorkBook)
    ReleaseComObject(xlWorkBooks)
    ReleaseComObject(xlApp)
    Else
    MessageBox.Show("'" & FileName & "' not located. Try one of the write examples first.")
    End If
    Return dt
    End Function
    Private Sub ReleaseComObject(ByVal sender As Object)
    Try
    If sender IsNot Nothing Then
    System.Runtime.InteropServices.Marshal.ReleaseComObject(sender)
    sender = Nothing
    End If
    Catch ex As Exception
    sender = Nothing
    End Try
    End Sub
    End Module
    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

  • Create Object Array

    I am trying to do a simple task that I thought would be very easy and quick to do but I have run into problems
    I am trying to get the user to input a number and based on that number make a text field to become visible based on it. So if the user input 3 the first 3 textfields would become visible. I have 10 textfields and I don't need any error handling yet as I can do that later but this is my code:
    var x=NumericField1.rawValue;
    for(var i=0; i<=x; i++)
    TextField1[i].presence="visible";
    I think my problem is creating the object array as all I did was double clicked in the library to create the textfields and the names come up as TextField1 then in the grey shaded area right beside it is the number 0. The next one is called TextField1 with 1 greyed out beside it.
    Can anyone help me out?
    Thanks

    SO IF YOU TRY IN JAVASCRIPT THIS WON'T WORK SO DO THIS IN "FORMCALC"
    i=NUMIRICFIELD.RAWVALUE;
    TextField1[i].presence="visible";
    PLEASE DO THIS IN FORMCALC &FEEDBACK ME
    [email protected]

  • Abstract  object array  initialization

    Hi everybody!
    I have a question, I know you can help me.
    I created an abstract class called publication, and two other clases called Tape and Book that derive from the publication class. Now, in the application I have :
    Publication BookTape[];
    when I compile my program I have one error which is that I haven't initialize the BookTape[] object array. My question is How I can initialize an object that comes from an abstract class? could you help me?
    Thank you !!!

    Publication bookTapes[] = new Publication[10];That will create your array (note, this has nothing to do with instantiating abstract classes).
    If you actually want to have something in your array, you need to fill it with subclasses of Publication since it's an abstract class.
    So.
    for(int i = 0;i < bookTapes.length;i++)
       bookTapes[i] = new SubclassOfPublication();

  • Initializing object array

    Hi,
    I am having problem initializing object array - here is my scenario -
    I have created class a -
    public class A {
    Public String a1;
    Public String a2;
    Public String a3;
    }the I have created class b
    public class B {
    Public A [] aa;
    }and I want to initialiaze my class bi in anoither clas c
    public class C{
    A ar = new A;
    ar.aa[0].a1 = "test"
    }this gives me null ..please anybody help me
    Neha
    }

    Thanks for the reply ..I know this is not good code ..but I have to write the classes in this way in SAP to create the Webservice ...the SAP side understand this type of structure only ..I still got the same error ..here are my original classes -
    public class GRDataItem {
         public String AUFNR ;
         public String EXIDP ;
         public String EXIDC;
         public String MATNR ;
         public String WERKS ;
         public String CHARG ;
         public String VEMNG ;
         public String VEMEH ;
         public String CWMVEMEH ;
         public String CWMVEMNG ;
         public String STATUS;
    public class GRDataTab {
         public GRDataItem [] grItem;
    Public class webservice {
                int sn = 20 ;
                  GRDataTab tab = new GRDataTab();
                tab.grItem = new GRDataItem[sn];
                tab.grItem[1].AUFNR = "12";
    }Thanks for all your help
    Neha

  • Search in object array

    I am working on a program in which one of the problems is to search an object array to allow a user to edit an item in the array. I have examples on how to do linear and binary searches, but they are all simple strings of numeric data. How do I apply this algorithm to a more complex array?I have a class file called Application that contains my constructor, and my get & set methods for creating the objects in the array. And I have a driver class to allow a user to view the array, add items to it , and edit items in it.
    This is an example of my declaration of the initial items:
    Application inventory[] = new Application[100];
      inventory[0] = new Application("Jumpstart Toddlers", 14.99, 500);
      inventory[1] = new Application("Norton Antivirus 2003", 49.99, 1200);
      etc....
    I would like to set it up so that the user is prompted for the name of the software item they would like to edit, the array is searched using a method which returns the index the name was found in.

    Sounds like a homework assignment to me but...
    Appliction apps[] = new Application[100];
    ...Add Items to the apps array...
    String software_to_search_for = .. user entered
    data....
    for (int i = 0; i < apps.length; ++i)
    if
    f
    (apps.getSoftware().equalsIgnoreCase(software_to_sea
    ch_for))
    edit(apps[i], software_to_search_for);
    public void edit(Application app, String newName)
    // You can do anything here
    app.setName(newName);
    } // edit
    True enough, this is an assignment. But..These assignments were given to us without all the necessary tools. They are set up by the dept. and we have to finish them even if the instructor does not finish covering all the relevant material.In this case, we have not covered the equalsIgnoreCase(something obviously necessary for my problem). Now that I know what I am looking for, I have found it in my book and can apply it to my code appropriately. I was not necessarily looking for code, just the tools I need for my own design. This is something that the Computer dept. allows for in that they have assistants in the open labs that will help in this manner. Problem is, everyone has been out for Thanksgiving since Tues. Please dont feel as though you assisted someone in cheating!! I can assure you, that is not the case here. Thank you for your help.

  • Can u have a spry data set Object array.....

    Ok this is what i need to do. I need a spry object array to
    be created with in a function.
    Just like this.....
    <!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"
    xmlns:spry="
    http://ns.adobe.com/spry">
    <head>
    <meta http-equiv="Content-Type" content="text/html;
    charset=iso-8859-1" />
    <title>Hijax Demo - Notes 1</title>
    <script language="JavaScript" type="text/javascript"
    src="includes/xpath.js"></script>
    <script language="JavaScript" type="text/javascript"
    src="includes/SpryData.js"></script>
    <script language="JavaScript" type="text/javascript">
    * @author nadeerak
    function test5(){
    funObjects = new Array();
    funObjectsObserver = new Array();
    funListList = new Array();
    x = new Array();
    x[0] = "First";
    x[1] = "Second";
    x[2] = "Third";
    x[3] = "Fourth";
    for(y in x)
    funObjects[x[y]] = new
    Spry.Data.XMLDataSet("notes"+y+".xml", "notes/note");
    funObjectsObserver[x[y]] = new Object;
    funListList[x[y]] = null;
    funObjects[x[y]].useCache = false;
    funObjects[x[y]].loadData();
    funObjectsObserver[x[y]].onDataChanged = function(dataSet,
    data)
    funListList[x[y]]=funObjects[x[y]].getData();
    alert(funListList[x[y]].length);
    funObjectsObserver[x[y]].onPreLoad = function(dataSet, data)
    alert("preload");
    funObjectsObserver[x[y]].onPostLoad = function(dataSet,
    data)
    funObjects[x[y]].addObserver(funObjectsObserver[x[y]]);
    </script>
    </head>
    <body>
    <input type="button" value="button" name="button"
    onclick="test5();">
    </body>
    </html>
    i have note0.xml to note6.xml
    once the button clicked i need all the alerts to give the
    length. But this dyanimically created objects does not load. Why?
    Can we do something like this in SPY? like creating a spry
    object array........... can we?
    The error im getting is after two alerts i get
    "funListList[]. is null or not an object " individually it works
    very well?
    why is this?
    To my knowladge the data is not loaded after the second....
    Hmmmm how come? im using seperate objects....
    PLS ALL SPRY LOVERS help me......

    Hi,
    Check this sample:
    http://labs.adobe.com/technologies/spry/samples/DataSetSample.html
    Check the source code to see how we build a data set from an
    array.
    Hope this helps,
    Donald Booth
    Adobe Spry Team

  • Saving An Object Array to a File

    Please Help,
    I am fairly new to Java. I am trying to write a program that inputs merchandise information (ItemName, Description, Price, etc�) to an object array. The program works internally with the array perfectly, but I can�t get it to save the array to a file so it can be read and reused the next time the program is run. The class the array is built on implements Serializable, but when it tries to save it to a file, it throws an exception message saying that my object is not serializable.
    Does anyone have some code to help me save information to an array (so it can be used within the program), save the array to a disk file, and read the file back into the program the next time the program opens?
    Thank you,
    Bob

    Thank you for your help. The total code is quite lengthy so I�ve tried to pick the most relevant code to include here.
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.text.*;
    import java.io.*;
    public class Class1 extends WindowAdapter implements ActionListener
    // Object Array Declaration.
    ItemInfo ItemArray[] = new ItemInfo[100];
    * This is the Inner Class that the Array is built on. I have two constructors in it because I
    * tried several different methods to make this write to the disk file
    public class ItemInfo implements Serializable
         int ItemNum;
         int DeptNum;
         String ItemName;
         String Model;
         String Description;
         float Price;
         int Units;
    // Constructors
         public ItemInfo() {};
         public ItemInfo(int inItemNum, int inDeptNum, String
                             inItemName, String inModel, String
                             inDescription, float inPrice, int inUnits)
              ItemNum = inItemNum;
              DeptNum = inDeptNum;
              ItemName = inItemName;
              Model = inModel;
              Description = inDescription;
              Price = inPrice;
              Units = inUnits;
    } // end class ItemInfo.
    * openOutputStream() *
         private void openOutputStream()
              try
              // create file and output object streams
                   outputItemFile = new FileOutputStream("A:ItemFile.txt");
                   objSaveItems = new ObjectOutputStream(outputItemFile);
              } // end try
              catch (Exception error)
                   System.err.println("Error opening file");
              } // end catch
         } // end openOutputStream().
    * closeOutputStream() *
         private void closeOutputStream()
              try
                   objSaveItems.close();
                   outputItemFile.close();
              catch (IOException error)
                   System.err.println("Error Closing File");
              } // end catch
         } // end closeOutputStream().
    * AddToItemArray() - This method just assigns the information to the Array elements *
         private void AddToItemArray()
              int ArrayNum = intItemFileSize - 1;
              ItemArray[ArrayNum] = new ItemInfo();
              ItemArray[ArrayNum].ItemNum = intNewItemNum;
              ItemArray[ArrayNum].DeptNum = intDeptNum;
              ItemArray[ArrayNum].ItemName = strItemName;
              ItemArray[ArrayNum].Model = strModel;
              ItemArray[ArrayNum].Description = strDescription;
              ItemArray[ArrayNum].Price = fltPrice;
              ItemArray[ArrayNum].Units = intUnits;
         } // end AddToItemArray().
    * WriteToFile() - This is the latest effort to write to the file. The file gets opened, and
    * the first element gets printed, but after that nothing but error messages (printed * below).
         private void WriteToFile()
              try
                   openOutputStream();
                   for (int a = 0; a <= intItemFileSize; a++)
                        objSaveItems.writeObject(ItemArray[a]);
                        objSaveItems.flush();
                   closeOutputStream();
              } // end try.
              catch (Exception error)
                   System.err.println("Error writing to file");
         } // end WriteToFile().
    This is what appears on the disk file after I run the program (three items entered):
    � sr Class1$ItemInfo�&q����B I DeptNumI ItemNumF PriceI UnitsL
    Descriptiont Ljava/lang/String;L ItemNamet Ljava/lang/String;L Modelt Ljava/lang/String;L this$0t LClass1;xp A��� t
    Claw Hammert Hammert CL550{sr  java.io.NotSerializableException(Vx �� 5   xr  java.io.ObjectStreamExceptiond��k�9��   xr  java.io.IOExceptionl�sde%��   xr  java.lang.Exception��> ; �   xr  java.lang.Throwable��5'9w��   L
    detailMessaget  Ljava/lang/String;xpt  Class1
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Generated WS client is unable to unmarshal returned object array

    Hello,
    I have created web service using Sun jaxws implementation. Several methods of this ws return object array (CustomObj []). When I generate the client (using jaxws-maven-plugin - wsimport) and call these methods I always get
    empty array. I get no errors or warnings. When I generate axis client all works as expected. I think that this issue is related to jaxb but i have tried to switch between several versions ant this didn't help. CustomObj is very simple object with two attributes name and value...
    Thanks for hints...

    Hi Shepy,
    I think mapping an array of objects as response in WSDL messages is somewhat of an issue.
    Instead try moving this array of object into another XSD if i assume you are using XSDs and then make sure that response XSD holds and array of your objects.
    Regards,
    Anand

  • Returning an Object Array

    I am unable to figure out the way in which I can return an object
    array from a cpp file to java. Is there any obvious error which you can spot in
    my CPP file?
    When I try to return a single object in the native function,
    it works fine but when I try to extend it and return an array of the object, it
    throws an error.
    Please find below the details
    h1. Java Class
    public class Flight {
    public String ID;
    public class InterfaceClass {
    private native Flight[] GetFlights();
    public static void main(String[] args)
    Flight[] objFlight = new
    InterfaceClass().GetFlights();
    System.+out+.println(objFlight[0].ID);
    static {
    System.+loadLibrary+("main");
    h1. CPP File
    JNIEXPORT jobjectArray JNICALL Java_InterfaceClass_GetFlights(JNIEnv env, jobject obj)
    //1. ACCESSING THE FLIGHT CLASS
    jclass cls_Flight = env->FindClass("LFlight;");
    //2. CONSTRUCTOR FOR FLIGHT CLASS
    jmethodID mid_Flight = env->GetMethodID(cls_Flight,"<init>", "()V");
    //3. CREATING AN OBJECT OF THE FLIGHT CLASS
    jobject objFlight = env->NewObject(cls_Flight, mid_Flight);
    //4. ACCESSING THE FLIGHT's "ID" FIELD
    jfieldID fid_ID = env->GetFieldID(cls_Flight, "ID","Ljava/lang/String;");
    //5. SETTING THE VALUE TO THE FLIGHT's "ID" FIELD
    env->SetObjectField(objFlight,fid_ID, env->NewStringUTF("ABC"));
    //6. ACCESSING THE FLIGHT ARRAY CLASS
    jclass cls_Flight_Array = env->FindClass("[LFlight;");
    if(cls_Flight_Array == NULL)
    printf("Error-1");
    //7. CREATING A NEW FLIGHT ARRAY OF SIZE 1 jobjectArray arrFlightArray = env->NewObjectArray(1,cls_Flight_Array,NULL);
    if(arrFlightArray == NULL)
    printf("Error-2");
    //8. INSERTING A FLIGHT BJECT TO THE ARRAY
    env->SetObjectArrayElement(arrFlightArray,0,objFlight);
    return arrFlightArray;
    h1. Error
    # A fatal error has been detected by the Java Runtime Environment:
    # EXCEPTION_ACCESS_VIOLATION
    (0xc0000005) at pc=0x6d9068d8, pid=1804, tid=3836
    # JRE version: 6.0_18-b07
    # Java VM: Java HotSpot(TM) Client VM (16.0-b13 mixed mode, sharing
    windows-x86
    # Problematic frame:
    # V [jvm.dll+0x1068d8]
    # An error report file with more information is saved as:
    # C:\Users\Amrish\Workspace\JNI Test\bin\hs_err_pid1804.log
    # If you would like to submit a bug report, please visit:
    http://java.sun.com/webapps/bugreport/crash.jsp
    C:\Users\Amrish\Workspace\JNI Test\bin>java -Djava.library.path=.
    InterfaceClass
    Exception in thread "main" java.lang.ArrayStoreException
    at
    InterfaceClass.GetFlights(Native Method)
    at
    InterfaceClass.main(InterfaceClass.java:6)
    C:\Users\Amrish\Workspace\JNI Test\bin>java -Djava.library.path=.
    InterfaceClass
    Exception in thread "main" java.lang.ArrayStoreException
    at
    InterfaceClass.GetFlights(Native Method)
    at
    InterfaceClass.main(InterfaceClass.java:6)
    Edited by: amrish_deep on Mar 18, 2010 7:40 PM
    Edited by: amrish_deep on Mar 18, 2010 7:40 PM

    //6. ACCESSING THE FLIGHT ARRAY CLASS
    jclass cls_Flight_Array = env->FindClass("[LFlight;");The argument to NewObjectArray is the +element+ class of the array you're about to create, not the +array+ class itself.

  • Is there any way to create BHO.dll (Browser Helper Object) for Mozilla. I have created done this with IE7. I like to migrate this to Mozilla. Please suggest me

    I have done a project to capture URL details and based on the data I need to do business process. I have implemented this project in Interner explorer using BHO (Browser Helper Object). I need to migrate this project to Mozilla. Please suggest me.

    Firefox doesn't use BHO like IE.
    For Firefox (and Google Chrome) you will have to create extensions to add extra features.
    *https://developer.mozilla.org/en/Extensions
    *https://developer.mozilla.org/en/Building_an_Extension

Maybe you are looking for

  • I have bought a new pc, and i want to move adobe lightroom frome my old computer to my new comuter.

    I have bought a new computer and I want to move adobe lightroom frome my old computer to my new computer, how do I do this?

  • Configuration Issue duplicate SID

    Hi, I am getting a duplicate SID (ABC1 (2)) on UNIX. I have checked all the possibilities how to remove it but unable to find it. As you you see below: ORATAB: ================================================ ABC1:/oraclehome/oracle10g:Y ============

  • Voucher Number with Forms Personalization

    I am trying to use forms personalization to accomplish the following: We've enabled vouchering in Payables and now each invoice, when saved, is assigned a voucher number. (INV_SUM_FOLDER.VOUCHER_NUM_DISPLAY). When you click the attachments icon, we w

  • Date format in Oracle reports

    Hello everyone, I need my report ro show dates with HH:MM:SS. But the report only shows dates as DD-MON-RR. I think I chose all the correct format masks in the report builder (DD-MON-RR HH24:MI:SS), and in the rtf tags. Another point is that all the

  • Custom Connector Run Time Variable Error.

    Hello community, I developed a custom connector to provision users to a target resource. Now here is my problem, after we create the sandbox, create an application instance, activate and publish the sandbox, and attempt the provisioning (probably mis