1

Ive got this kinda stupid exam question in which I'm told to make an array of objects IN MAIN method. I defined the class Account with two variables - String owner and double amount.

Then I'm told to make the Account class handle change of values sum of all amounts. etc. But I cant figure out what I'm doing wrong - I cannot get access to the array from getAmount().

public static void main(String[] args) 
{
    Account[] account = new Account[10];
    for ( int i=0; i<account.length; i++) 
    {
    account[i]=new Account();
    }
    account[0].owner = "Thomas";
    account[0].amount = 24325;
    System.out.println(getAmount(0)); //<- dont work,  but works with account[0].amount
}

public static double getAmount(int x) 
{
    double s = account[x].amount;   //<<------- CANNOT FIND SYMBOL
    return s;
}

2 Answers 2

2

account is local to the main method, so it can't be accessed from other methods unless passed to them as a parameter.

An alternative is to declare it as a static member:

static Account[] account = new Account[10];

public static void main(String[] args) 
{
    for ( int i=0; i<account.length; i++) 
    {
        account[i]=new Account();
    }
    account[0].owner = "Thomas";
    account[0].amount = 24325;
    System.out.println(getAmount(0));
}
Sign up to request clarification or add additional context in comments.

2 Comments

thing is that i'm told to make the array in the main method.
@ThomasWegener You can still initialize it in the main method, but you must declare it outside in order to access it from a different method. If you want to keep it local to main, getAmount can accept the array as a parameter - getAmount(account,0)
1

In this case account is a local variable for main, if you want to use the method getAmount you have two options: -Declare the array as static and put it out of the main method (the array would be a global variable) -Pass the array as a parameter in getAmount.

public static void main(String[] args) 
{
    Account[] account = new Account[10];
    for ( int i=0; i<account.length; i++) 
    {
    account[i]=new Account();
    }
    account[0].owner = "Thomas";
    account[0].amount = 24325;
    System.out.println(getAmount(0), account); //<- dont work,  but works with account[0].amount
}
public static double getAmount(int x, Account[] account) 
{
    double s = account[x].amount;   //<<------- CANNOT FIND SYMBOL
    return s;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.