I tried to loop through a string array such that for each value, it calls dynamically the setter method named with it, e.g one.set"holdingArray[i]"(a);. Is there a way to achieve this behavior?
Here is a code example to illustrate my problem. The line one.setholdingArray[i](a); is compiling and must be changed.
class Troops {
private int barbarian;
private int archer;
private int goblin;
private int giant;
private String[] holdingArray = {
"Barbarian",
"Archer",
"Goblin",
"Giant",
};
int getBarbarian() {
return barbarian;
}
int getArcher() {
return archer;
}
int getGoblin() {
return goblin;
}
int getGiant() {
return giant;
}
void setBarbarian(int barb) {
barbarian = barb * 150;
}
void setArcher(int a) {
archer = a * 300;
}
void setGoblin(int g) {
goblin = g * 80;
}
void setGiant(int gi) {
giant = gi * 2250;
}
class HelloWorld {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
Troops one = new Troops();
int a;
for(int i = 0; i < holdingArray.length; i++) {
System.out.println("How many " + holdingArray[i] + " do you have??");
a = in.nextInt();
// TODO this line must be changed with the answer
one.setholdingArray[i](a);
System.out.println();
}
}
}
myArray[i] = x3. Your array is private, so it can't be modified or even accessed by code from outside of the class.one.setholdingArray[i](a);This line makes no sense. First of all, ClassTroophas no methodsetHoldingArray, and second, you then try to do an array access on it, which isn't valid syntax.