tags:

views:

49

answers:

4

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++) {
         String 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?

+2  A: 

why aren't you using an array instead?

Jan Kuboschek
+5  A: 

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"});
Péter Török
+1 - I recommend this approach. What you describe that is valid for VB can be made with Reflection - you want to dynamically form names of variables.
Leni Kirilov
A: 

As @Jan Kuboschek points out, you should be using an array. Failing that, check out reflection.

Hank Gay
A: 

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.

Rajat
Not the most graceful of workarounds...but I passed the dynamic string variable as a single string to the function and simply spilt it into an array based on a "," delimiter...
Rajat