Reputation: 45
I'm struggling a bit finding how to send/access an object that has been created in the main method by another static method.
Here is my some of my service class code, which consists of public constructor, accessor and mutator methods:
public class Participants
{
String firstName=" ";
String lastName=" ";
int socialSecurity=0;
int ticket=0;
char status='N';
Vehicle veh=null;
public Participants(String fn, String ln, int ssn, int tkt)
{
firstName=fn;
lastName=ln;
socialSecurity=ssn;
ticket=tkt;
}
}
And there is the Client class, which has the main method where I created and initialized those objects and second method which I'm trying to access those objects:
public class Race
{
public static void main(String[] args)
{
....
Participants []people=new Participants[35];
Vehicle []cars=new Vehicle[10];
...code to "fill" those objects
GiveAway([]cars,[]people); //sending those objects to static method- doesn't work from here)
}
public static void GiveAway(Vehicle[] veh, Participants[] part)
{
//set of instructions to work and change those objects
}
}
The code simply doesn't work and it is because I don't really know how to either "send" an object array to an method (is that possible, by the way?).
Am I doing it the right way? Or there is an easier way around? I found some subjects about private classes and everything else, but couldn't figure out what to do with my code.
I appreciate any help
Thank you!
Upvotes: 1
Views: 787
Reputation: 19
Participants []people=new Participants[35];
Vehicle []cars=new Vehicle[10];
GiveAway([]cars,[]people);
should be
Participants[] people=new Participants[35];
Vehicle[] cars=new Vehicle[10];
GiveAway(cars, people);
In Java you use the [] to signal the compiler that this is an array. you put it right behind the name of the Object you want to create an array of (Participants, Vehicle). And when calling "GiveAway" you only need to use the names of the arrays.
Upvotes: 1
Reputation: 34618
I think that you believe that the array name is []people
and []cars
. It's not. When you declare them, it's actually:
Vehicle[] cars = new Vehicle[10];
└───────┘ └──┘
Type var name
So the array is named cars
, and that's how you should pass it to the other method:
GiveAway(cars, people);
As a side note: don't give methods names that begin with a capital letter. The conventions are that only type names (classes, interfaces, etc) begin with a capital letter. Constants are all-caps, and methods have a lowercase first letter.
Upvotes: 2
Reputation: 4891
Your call to GiveAway
should look like this
GiveAway(cars, people);
Those square brackets are giving you a compiler error.
Upvotes: 1