如何通过组合两个不同的变量来创建变量名

时间:2019-06-12 09:23:45

标签: java selenium selenium-webdriver

我从CSV文件中获取值,然后将其存储在字符串中,现在这些字符串是我在Selenium中使用sendKeys传递的数据。现在,我想将那些String的变量与for循环计数结合起来,那么我该怎么做?

String csvFile = "/home/Miscellaneous/demo.csv";
CSVReader csv_reader = new CSVReader(new FileReader(csvFile));
List<String[]> strings = csv_reader.readAll();
for(int dime=2 ;dime<strings.size() ;dime++)
{
//Get data from csv file
    String[] csvCell = strings.get(dime);
    String no_of_new_rows_temp = csvCell[2];
    Integer no_of_new_rows = Integer.valueOf(no_of_new_rows_temp);
    String dim_label_1 = csvCell[3];

    for (int no_of_new_rows_fill = 0; no_of_new_rows_fill <= no_of_new_rows; no_of_new_rows_fill++)
    {
//Add Dimentions
        driver.findElement(By.name("dimension[label]["+no_of_new_rows_fill+"]")).sendKeys("dim_label_" + no_of_new_rows_fill);
    }
}

上面的代码确实返回了我的期望,但是它是一个字符串,而我需要它作为一个变量。

我的期望输出应采用sendKeys中应创建的“ dim_label_”和“ no_of_new_rows_fill”的方式

dim_label_1

通过这种方式,我可以将dim_label_1的CSV文件数据发送到该字段。

1 个答案:

答案 0 :(得分:1)

无法在Java中创建动态变量。但是您可以在这里利用Java集合来解决此问题

 String csvFile = "/home/Miscellaneous/demo.csv";
 CSVReader csv_reader = new CSVReader(new FileReader(csvFile));
 List<String[]> strings = csv_reader.readAll();
 Map<String,String> map = new HashMap()<String,String>;
 for(int dime=2 ;dime<strings.size() ;dime++)
 {
 //Get data from csv file
     String[] csvCell = strings.get(dime);
     String no_of_new_rows_temp = csvCell[2];
     Integer no_of_new_rows = Integer.valueOf(no_of_new_rows_temp);
     //String dim_label_1 = csvCell[3];
    map.put("dim_label"+dime,csvCell[3]);
     for (int no_of_new_rows_fill = 0; no_of_new_rows_fill <= no_of_new_rows; no_of_new_rows_fill++)
     {
 //Add Dimentions
         //driver.findElement(By.name("dimension[label]["+no_of_new_rows_fill+"]")).sendKeys("dim_label_" + no_of_new_rows_fill);
        driver.findElement(By.name("dimension[label]["+no_of_new_rows_fill+"]")).sendKeys(map.get("dim_label_" + no_of_new_rows_fill));
     }
 }