Results 1 to 9 of 9

Thread: array of Object

  1. #1
    amit_m04 is offline Member
    Join Date
    Mar 2009
    Posts
    5
    Rep Power
    0

    Default array of Object

    Hi

    i want to create an array of object.
    i am creating a banking program in which i have create a new account and i want to live that option to the user as much as account he can create and so i want to create an array of objects so when the user says that he wants to add a new object should be created..
    is that possible..

    well i have tried doing


    classname[] veriable = new classname[]

    but in this case in the new classname[], i have to specify howmany array.. and if i just give

    classname[] variable

    variable[]= new class(,)

    it gives me error saying the variable is not initialized..

    please help

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    Arrays in Java have a fixed size. See, for instance, the discussion of arrays in Sun's Tutorial.

    One way to work within this restriction is to create a new array when you want to add a new item. Then you would copy the old contents to the new array and add the new element.

    A better way is to work with some sort of List, like an ArrayList. See Collections

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    Quote Originally Posted by amit_m04 View Post
    it gives me error saying the variable is not initialized.
    If that is a compiler message (rather than an error), you will get the best help if you can post the exact and entire message and also the code it refers to. (Not an approximate code sniplet, but the actual code you are trying to compile.)

  4. #4
    emceenugget is offline Senior Member
    Join Date
    Sep 2008
    Posts
    564
    Rep Power
    7

    Default

    Quote Originally Posted by amit_m04 View Post
    Hi

    i want to create an array of object.
    i am creating a banking program in which i have create a new account and i want to live that option to the user as much as account he can create and so i want to create an array of objects so when the user says that he wants to add a new object should be created..
    is that possible..

    well i have tried doing


    classname[] veriable = new classname[]

    but in this case in the new classname[], i have to specify howmany array.. and if i just give

    classname[] variable

    variable[]= new class(,)

    it gives me error saying the variable is not initialized..

    please help
    arrays must have a specific size:
    classname arr[] = new classname[ ARRAYSIZE ]; // initializes the array
    after this, you can initialize the individual "classname" objects in the array.

  5. #5
    amit_m04 is offline Member
    Join Date
    Mar 2009
    Posts
    5
    Rep Power
    0

    Default array of Object

    Hi

    below is the my code as it was my first assignment and i have just started java.




    import java.io.*;
    import java.lang.*;


    class UserException extends Exception
    {
    public UserException()
    {
    super();
    }
    public UserException(String str)
    {
    super(str);
    }
    }

    class BnkDtls
    {
    int ac_no;
    static short a_c=1;
    String Fname, msg;
    float bal;

    BnkDtls(String nm)
    {
    ac_no=a_c++;
    Fname=nm;
    bal=500f;
    }

    BnkDtls(String nm, float amt)
    {
    ac_no=a_c++;
    Fname=nm;
    bal=amt;
    }

    void Deposit(float amt)
    {
    bal=bal+amt;
    }

    void withdrw(float a)
    {
    try
    {
    if((bal-a)<500)
    {
    msg="\n Avalibale balance for Withdrawl: "+(bal-500);
    throw new UserException(msg);
    }
    else
    { if((bal==500) && (a==bal))
    {
    msg=" Not Enough balance";
    throw new UserException(msg);
    }
    else
    bal=bal-a;
    }
    display();
    }

    catch(UserException ee1)
    {
    System.out.println(ee1.getMessage());
    }
    }

    void display()
    {
    System.out.print("\n Account No : "+ac_no);
    System.out.print("\n Fname : "+Fname);
    System.out.print("\n Available Balance : "+bal);
    System.out.print("\n");
    }
    }

    class Bank
    {
    public static void main(String arg[]) throws Exception
    {
    String FNam;
    int AC,Mn;
    float bl;

    Bank BB = new Bank();

    DataInputStream IN= new DataInputStream(System.in);
    BnkDtls B1= new BnkDtls("Deepak Patil");
    BnkDtls B2= new BnkDtls("Vikram Shinde", 1000.0f);

    BB.ClrScr();

    do
    {
    System.out.print("\n");
    System.out.print("\n ----- Menu ----");
    System.out.print("\n 1] Deposit Amount");
    System.out.print("\n 2] Withdraw Amount");
    System.out.print("\n 3] Print Account Dtls");
    System.out.print("\n 4] Exit");


    System.out.print("\n\nEnter Your Menu Option : ");
    Mn=Integer.parseInt(IN.readLine());
    System.out.print("\n");


    switch(Mn)
    {

    case 1: System.out.print("\nEnter Account No : ");
    AC=Integer.parseInt(IN.readLine());
    System.out.print("\nEnter New Amount : ");
    bl=Float.parseFloat(IN.readLine());
    if (AC==1)
    { B1.Deposit(bl);
    B1.display();}
    else if(AC==2)
    { B2.Deposit(bl);
    B1.display();}
    else
    System.out.println("\n Invalid Account No... "+AC);
    System.out.println("\n\nPress any key to continue...");
    IN.readLine();
    BB.ClrScr();
    break;

    case 3: System.out.print("Enter Account No: ");
    AC=Integer.parseInt(IN.readLine());
    if(AC==1)
    B1.display();
    else if(AC==2)
    B2.display();
    else
    System.out.println("\n Invalid Account No... "+AC);
    System.out.println("\n\nPress any key to continue...");
    IN.readLine();
    BB.ClrScr();
    break;

    case 2: System.out.print("\nEnter Account No: ");
    AC=Integer.parseInt(IN.readLine());
    System.out.print("\nEnter Amount to Withdraw: ");
    float bl1=Float.parseFloat(IN.readLine());
    System.out.println();
    if(AC==1)
    B1.withdrw(bl1);
    else if(AC==2)
    B2.withdrw(bl1);
    else
    System.out.println("\n Invalid Account No... "+AC);
    System.out.println("\n\nPress any key to continue...");
    IN.readLine();
    BB.ClrScr();
    break;
    default: System.out.println("\nInvalid Option");
    }
    }while (Mn!=4);
    }

    void ClrScr()
    {
    for(int ii=0; ii<80; ii++)
    System.out.println();
    }
    }


    Now in this code if i want to have more then 2 accounts then as many accounts i want i will have to create the number of Objects B1, B2, B3... Bn and i will have to declare those before, but i want to create the objects at runtime and so i will have to have an array of Objects. I dont know if i am right or wrong but i have just got a thought and want help on this.

  6. #6
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    First of all, when you post code highlight the code and then click the code button (marked #) so your code is properly formatted. Another way is to type the code tags yourself like this:

    [CODE]
    code = "goes here";
    [/CODE]

    As to the code itself there are a few things you could do:

    (1) Don't import java.lang.* because you don't need to
    (2) Use meangingful variable names and make them start with a lower case letter. For example BB -> bank and Mn -> menuOption. The same for class names (although they start with a capital: BnkDtls -> BankDetails (or AccountDetails, or just Account).
    (3) Use braces always. Even for one line if statements.
    (4) Use BufferedReader rather than DataInputStream - because the chances are that System.in is not a data input stream.

    Java Code:
    //DataInputStream IN = new DataInputStream(System.in);
    BufferedReader IN = new BufferedReader(new InputStreamReader(System.in));
    Did you read what I posted about arrays and List? And what was linked to?

    If you decide to go with arrays then (A) you would declare, initialise and populate an array rather than use the BBn

    Java Code:
    //BnkDtls B1 = new BnkDtls("Deepak Patil");
    //BnkDtls B2 = new BnkDtls("Vikram Shinde", 1000.0f);
        // declare and initialise an array for the account details
    BnkDtls[] detailsArr = new BnkDtls[2];
        // populate the array
    detailsArr[0] = new BnkDtls("Deepak Patil");
    detailsArr[1] = new BnkDtls("Vikram Shinde", 1000.0f);
    Then (B) you would use the array rather than the BBn variables in each of the case statements. Notice that things become a little complex with arrays - because the user can enter an integer that doesn't correspond to a valid account, either because the integer is too big (or too small) or because the array does not have a valid account at that position (because one hasn't been created yet). You would have to check for both things.

    I'll look at "case 3" as an example:

    Java Code:
        // get the account number
    AC = Integer.parseInt(IN.readLine());
    
    //if (AC == 1)
    //    B1.display();
    //else if (AC == 2)
    //    B2.display();
    //else
    //    System.out.println("\n Invalid Account No... " + AC);
    
        // check that it is a valid array member				
    if(AC <= detailsArr.length && AC > 0) {
        BnkDtls toShow = detailsArr[AC - 1];
            // check that an account with this number is present in the array
        if(toShow == null) {
            System.out.println("\n Invalid Account No... " + AC);
        } else {
                // only if an account exists with the given
                // number, display it
            toShow.display();
        }
    } else {
        System.out.println("\n Invalid Account No... " + AC);
    }
    (Notice that toShow=detailsArr[AC - 1] because arrays are zero based.)

    You can test all this by commenting out the bodies of the other case statements.

    To make further progress with this you are going to have to be very familiar with arrays. If the comments above about "zero based" and the need to declare, initialise and populate the array make no sense, then it's time to hit the books.

    Finally I should note that you have reached and exceeded by a good bit, the amount of stuff that can be reasonably made to fit into a main() method. You need to break up this method - and again the current project may have to be put aside until you are happy with that.

    Mistake edited. Also, when you have nested if statements some people like to put the shorter option first as this has the effect of keeping the "else" as close as possible to the "if". Following this convention the nested if statement given above is equivalent to:

    Java Code:
    if(AC > detailsArr.length || AC <= 0) {
        System.out.println("\n Invalid Account No... " + AC);
    } else {
        BnkDtls toShow = detailsArr[AC - 1];
        if(toShow == null) {
            System.out.println("\n Invalid Account No... " + AC);
        } else {
            toShow.display();
        }
    }
    Last edited by pbrockway2; 03-08-2009 at 12:24 AM.

  7. #7
    amit_m04 is offline Member
    Join Date
    Mar 2009
    Posts
    5
    Rep Power
    0

    Default

    Hi pbrockway2,

    thankyou for all those tips i'll take care of all those while i code.
    let me be very frank that i did not go through the links that you had provided with for Array and Collection, however the way you have provided the example and edited the code using the array i have got a fair idea about it.
    I tried to read with the list but as i have just started with java all's bouncing back...
    I would request you if you could pls give me some kinda example of list using the same code, it would be really of a gr8 help for me to understand fast.

  8. #8
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    It's very little different with list rather than array - the most obvious change is that the logic for checking the user supplied a/c number is simplified.

    (Like the array example, I'm assuming that the accounts are stored sequentially in a list without any "gaps". Not a particularly realistic assumption. More generally the account details would be associated in some way with a unique account number. The Collection built for this is a Map - read up about it and play if you want.)

    First before the do loop:

    Java Code:
    //BnkDtls B1 = new BnkDtls("Deepak Patil");
    //BnkDtls B2 = new BnkDtls("Vikram Shinde", 1000.0f);
    List<BnkDtls> detailsList = new ArrayList<BnkDtls>();
    detailsList.add(new BnkDtls("Deepak Patil"));
    detailsList.add(new BnkDtls("Vikram Shinde", 1000.0f));
    Then in the body of "case 3" - comment out the others to test:

    Java Code:
    AC = Integer.parseInt(IN.readLine());
    
    //if (AC == 1)
    //    B1.display();
    //else if (AC == 2)
    //    B2.display();
    //else
    //    System.out.println("\n Invalid Account No... " + AC);
    if(AC > detailsList.size() || AC <= 0) {
        System.out.println("\n Invalid Account No... " + AC);
    } else {
        detailsList.get(AC - 1).display();
    }

  9. #9
    Sylar's Avatar
    Sylar is offline Member
    Join Date
    Mar 2009
    Location
    Odessa, Texas
    Posts
    16
    Rep Power
    0

    Default

    I suggest you use a LinkedList Structure instead of an array

    this way you wouldnt have trouble expanding your list

Similar Threads

  1. Adding elements to an Object Array
    By aneesahamedaa in forum New To Java
    Replies: 4
    Last Post: 09-07-2008, 04:55 PM
  2. initialising Array of object??
    By Somitesh Chakraborty in forum New To Java
    Replies: 4
    Last Post: 08-27-2008, 10:00 PM
  3. Array of Object
    By haiforhussain in forum New To Java
    Replies: 1
    Last Post: 06-25-2008, 12:24 PM
  4. Need help with creating array of type object
    By riz618 in forum New To Java
    Replies: 3
    Last Post: 01-29-2008, 07:14 AM
  5. Object array query
    By bugger in forum New To Java
    Replies: 5
    Last Post: 01-07-2008, 06:58 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •