Reputation: 395
I'm a bit mixed up. Here is my work so far.
public class CourseYear
{
private String courseName;
private int year;
private String tutorName;
private String [] moduleList;
The moduleList is to hold 6 modules
public CourseYear()
{
courseName = "Default";
year = 0;
tutorName = "Joe Bloggs";
moduleList = new String [5];
}
This is where my problem lies, I'm not sure how to do the array parts:
public void addModule(Module newModule, int index)
{
Module = newModule[0];
Module = newModule[1];
Module = newModule[2];
Module = newModule[3];
Module = newModule[4];
Module = newModule[5];
}
I have no idea how to do the get methods
public Module getModule(int index)
{
return Module[index];
}
Upvotes: 3
Views: 28545
Reputation: 120188
you need to reference your array with the index. In your class definition you need a
private Module[] modules = new Module[6]; // initialize
If you want your Array to contain Module
instances, the array needs to be an array of Modules. Right now your class has a String
array.
and then your add method becomes
public void addModule(Module newModule, int index){
this.modules[index] = newModule; // put the instance in the correct bucket
}
Note a few things:
1). Your array has 6 buckets, so the indexes allowed are 0-5. If index in the addModule
method is out of bounds you will get an exception.
2). addModule
expects newModule
to be a module instance. So you use addModule like
CourseYear courseYear = new CourseYear(); // create a courseyear
courseYear.addModule(new Module(), 0); // create a module and add it at index 0
courseYear.addModule(new Module(), 1); // create a module and add it at index 1
...
You can also use addModule
inside the CourseYear
class. Say you want to initialize in your constructor
public CourseYear(){
this.addModule(new Module(), 0); // create a module and add it at index 0
this.addModule(new Module(), 1); // create a module and add it at index 1
...
}
You should be able to figure out getModule
Upvotes: 2
Reputation: 231
public class CourseYear
{
private String courseName;
private int year;
private String tutorName;
private Module[] moduleList;
public CourseYear()
{
courseName = "Default";
year = 0;
tutorName = "Joe Bloggs";
moduleList = new Module[6];
}
public void addModule(Module newModule, int index)
{
moduleList[index] = newModule;
}
public Module getModule(int index)
{
return moduleList[index];
}
Upvotes: 2
Reputation: 47608
Two things.
1.If you want to hold 6 values in moduleList, you should instantiate with new String[6]
.
2.You will simplify your life by using an object of type List<String>
instead of having to maintain an index and so forth:
List<String> moduleList = new ArrayList<String>();
It's dynamic and simple to use.
Upvotes: 1
Reputation: 2436
I assume you wanted to write get and set methods for moduleList. The signatures would be
public void setModuleList(String[] module);
public String[] getModuleList();
Once you get the list, you can retrieve the items in the list.
Upvotes: 0