使用 ArrayList 作为函数调用 Java

Using ArrayList as function call Java

public class TestClass extends BaseClass {
    public void getquote() {
        String FirstName = "Sam";
        String LastName = "Gayle";
        String Email = "somename@somename.com";
        String Password = "test1234";
        CallGetQuote(FirstName, LastName, Email, Password);
}

private void CallGetQuote(String... var) {
    for (int i = 0; i < var.length; i++) {
        driver.findElement(By.id("first-name")).sendKeys(var[i]);
        driver.findElement(By.id("last-name")).sendKeys(var[i]);
        driver.findElement(By.id("join-email")).sendKeys(var[i]);
        driver.findElement(By.id("join-password")).sendKeys(var[i]);
        // driver.findElement(By.name("btn-submit")).click();
    }
}

}

`我想使用循环而不是前面提到的硬编码索引号来填充对象。上面是我写的,此刻,所有文本框都填充了所有值。请帮助:(

谢谢。`

您可以使用 varargs,更多信息可以在 JLS:

中找到

You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method.

因此,您的代码将类似于:

    public void getquote() {

        String firstName = "Sam";
        String lastName = "Gayle";
        String email = "somename@somename.com";
        String password = "test1234";

        CallGetQuote(FirstName, LastName, Email, Password);

    }

    public void CallGetQuote(String... var) {

        // add your elements to a List
        List<MyElements> inputElements = new ArrayList<MyElements>;

        inputElements.add(driver.findElement(By.id("first-name")));
        inputElements.add(driver.findElement(By.id("last-name"))); 
        inputElements.add(driver.findElement(By.id("join-email")));  
        inputElements.add(driver.findElement(By.id("join-password")));

        // iterate over the List to send keys
        for (int i = 0; i < var.length; i++) {
        inputElements.get(i).sendKeys(var[i]);
    }
    }

您可以创建一个 class 来代替传递 array/list,其中包含所有变量以及每个变量的访问器和修饰函数。在 getQuote() 中创建 class 的对象并将值附加到同一函数中。稍后您可以简单地传递对象。

只要您有新属性,您只需将属性添加到 class 并在任何地方使用该对象。

考虑到您在网页上只有指定数量的输入,您可以这样尝试。

public void getquote() {
    String FirstName = "Sam";
    String LastName = "Gayle";
    String ZipCode = "10104";
    String PhoneNumber = "212-225-8558";
    CallGetQuote(FirstName, LastName, ZipCode, PhoneNumber);
}

public void CallGetQuote(String... var) {
    List<Webelement> inputs = driver.findElements(By.tagName("input"));
    for (int i = 0; i < var.length; i++) {
        inputs.get(i).sendKeys(var[i]);
    }

}

您可能需要更改发送字符串的顺序。