I want call method path from class Path. I need set some number – array length and appropriate values of array on entrance.
This is my class:
class Path {
int number;
String[] path_name = new String [number];
Path (int n, String [] p){
number=n;
path_name=p;
}
public void path(){
for (int i=1; i<number; i++){
driver.findElement(By.linkText(path_name[i])).click();
}
}
}
This is how I try call method:
Path pa = new Path (6,'array value');
pa.path();
But I don’t know how properly initiate ‘array value’ – I need set “one”, “two”,”three” for example. Could someone help?
I do not know length of array on the beginning, so I can’t define several Strings in the constructor
There are multiple problems in your class.
First of the initialization of variables that is written directly at the class variables is done before the constructor body is executed. So your initialization of the
path_namearray will always by done with the default value ofnumberand that is0. This works but your array won’t be able to store any values this way.Now in your body, I guess you try to fill your
path_namearray with the content of theparray. But instead you replace the instance. This works just fine but in case anyone changes the array outside the class it will change in this class as well. I guess you want to transfer the values usingSystem.arraycopyorArrays.copyOf.For the call of your constructor you have to call something like this:
As improvement I suggest you drop the
numbervariable entirely how ever because you can at all time refer to the size of the array itself usingpath_name.length.Another thing you might want to look into is variable length arguments. If you change your constructor like this:
You set that there is a undefined amount of strings to be added after the number in the call of the constructor. All this strings are automatically packed in a String array called
p. As this array only exists inside this constructor you can safely copy the instance instead of the variables. The call of the constructor then looks like this: