I have been using this "logic" in C++ and VB with success, but am tied up in Java... Simply put,
public void DataProviderExample(String user, String pwd, String no_of_links,
String link1, String link2, String link3) {
for (int i=1;i<=no_of_links;i++) {
Strin开发者_运维问答g link = "link"+i;
System.out.println(link);
}
Now, if the variables link1
, link2
and link3
have a value of "X", "Y" and "Z" respectively, upon running this program, I get the following output -
link1
link2
link3
What I want is -
X
Y
Z
Any ideas?
You could use varargs:
public void DataProviderExample(String user, String pwd, String... links) {
for (String link : links) {
System.out.println(link);
}
}
...
DataProviderExample("user1", "password1", "X", "Y", "Z");
DataProviderExample("user2", "password2", "Q");
This way you can pass in the desired number of links, and the runtime automagically puts these into an array, which you can iterate over with a foreach loop.
With a plain array, calls would be more cumbersome (unless you already have the links in an array, of course):
public void DataProviderExample(String user, String pwd, String[] links) { ... }
DataProviderExample("user1", "password1", new String[] {"X", "Y", "Z"});
why aren't you using an array instead?
As @Jan Kuboschek points out, you should be using an array. Failing that, check out reflection.
I appreciate the answer. I am attempting to retrieve the parameters for the function from an external Excel file. Trying both the approaches you describe, I encounter a "java.lang.IllegalArgumentException: argument type mismatch" error. Any ideas why? :)
Declaration: DataProviderExample(String user,String pwd,String...links) {...} Calls: DataProviderExample("user1","pwd1","X","Y","Z"); DataProviderExample("user2","pwd2","X","Y");
I also tried the "array" approach and got the same argument mismatch error. Declaration: DataProviderExample(String user,String pwd,String[] links) {...} Calls: DataProviderExample("user1","pwd1",{"X","Y","Z"}); DataProviderExample("user2","pwd2",{"X","Y"});
Again, the parameters, user1, user2, pwd1, pwd2 and the links array are being retrieved from an Excel file.
Thanks.
精彩评论