I'm trying to get this method to create two instances of the class 'Sport'. The method is passing in a array which has the information about the class which is then sent to the constructor to be created.
However, I'm unsure how to refer to instance 1 or 2 given my code.
public static void seperateValues(String sportDetail) {
String[] sportDetails = sportDetail.split(",");
System.out.println("Adding new sport to the Sport collection");
System.out.println(sportDetail);
/*
for(int i=0; i<sportDetails.length; i++) //just used for testing whether it was splitting correctly {
System.out.println(sportDetails[i]);
}*/
//name,usagefee,insurance,affiliationfees, then court numbers
//Tennis,44,10,93,10,11,12,13,14,15,16
int vlength;
vlength = sportDetail.length();
new Sport(sportDetails); //this static methods loops twice, giving tennis and baseball
System.out.println(name); //this lists tennis and baseball respectively
}
If you just want to refer to two instances of sport, you can simply do this:
Sport sport1 = new Sport(sportDetails);
Sport sport2 = new Sport(sportDetails);
And then simply call sport1
or sport2
when you want to access them, however if you want to use that method n number of times for n number of sports, you can do this: First change the separateValues()
method to return a sport, by changing these lines:
public static void seperateValues(String sportDetail) {
to
public static Sport seperateValues(String sportDetail) {
At the end of the method, make it return a sport, like this:
Sport sport = new Sport(sportDetails);
return sport;
And then you can call the method inside a loop and create a list, so you can create as many sports are you need:
//First declare a list of sports:
List<Sport> sports = null;
for (int i = 0; i<asManySportsAsYouWantToAdd; i++){
sports.add(separateValues(sportDetail));
}
And then, to access each individual sport, you can simple use:
sports.get(n); //Where n is place of the sport on the list
Assuming your original string sportDetail
was "tennis,baseball", which then turned into an array of 2 terms, such as sportDetails[0] = "tennis"
and sportDetails[1] = "baseball"
, then within your class Sport
you simply need to reference them as such.
In other words, sportDetails[0]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.