首页 > 解决方案 > Wed 使用 Array 单单元和双位单元按升序对元素进行排序

问题描述

我可以使用下面的代码按升序排序,但由于单个单位和两位数单位(表示 9、19、5、12)它没有相应地排序

这是动态表,我必须在其中验证升序和降序。

        String temp = null;
    List<WebElement> editicons1 = driver.findElements(By.xpath("//mat-table//mat-row/mat-cell[2]"));
    String strArray[] = new String[editicons1.size()];
    for (int i = 0; i < editicons1.size(); i++) {
        editicons1 = driver.findElements(By.xpath("//mat-table//mat-row/mat-cell[2]"));
        Reporter.log(AddRule + " Cloumn as per display order " + editicons1.get(i).getText());
        Add_Log.info(AddRule + " Cloumn as per display order " + editicons1.get(i).getText());
        // System.out.println(editicons1.get(i).getText());
        strArray[i] = editicons1.get(i).getText();
    }
    // Sort the Array by Swapping the Elements
    for (int i = 0; i < strArray.length; i++) {
        for (int j = i + 1; j < strArray.length; j++) {
            if (strArray[i].compareTo(strArray[j]) < 0) {
                temp = strArray[i];
                strArray[i] = strArray[j];
                strArray[j] = temp;
            }
        }
    }
    // Printing the Values after sorting in ascending order
    System.out.println("##################Sorted values in the Array and compare order####################");
    for (int i = 0; i < strArray.length; i++) {
         System.out.println(strArray[i]);
    }
    for (int i = 0; i < strArray.length; i++) {
        if (strArray[i].contentEquals(editicons1.get(i).getText())) {
            // if (strArray[i].compareTo(editicons1.get(i).getText()) != 0) {
            Reporter.log(AddRule + strArray[i] + " Cloumn is display in  Ascending order");
            Add_Log.info(AddRule + strArray[i] + " Cloumn is display in  Ascending order");
        } else {
            Reporter.log(AddRule + " Cloumn is not in order");
            Add_Log.info(AddRule + " Cloumn is not in order");
            Assert.fail();
        }
    }

输出

No. Cloumn as per display order 5
No. Cloumn as per display order 7
No. Cloumn as per display order 8
No. Cloumn as per display order 10
No. Cloumn as per display order 11
No. Cloumn as per display order 12
No. Cloumn as per display order 19
No. Cloumn as per display order 22
No. Cloumn as per display order 92
No. Cloumn as per display order 96
No. Cloumn as per display order 98
No. Cloumn as per display order 99
##################Sorted values in the Array and compare order####################
99
98
96
92
8
7
5
22
19
12
11
10
No. Cloumn is not in order

如何更正单双单元号的排序顺序。

标签: javaarraysselenium-webdriver

解决方案


比较是在这一行进行的

if (strArray[i].compareTo(strArray[j]) > 0) {
 ...

为了将排序顺序从升序更改为降序,您只需更改><

编辑

正如其他人评论的那样,为了按数值排序,您需要将字符串转换为数字。您可以通过将上述内容更改为:

if (Integer.compare(Integer.parseInt(strArray[i]), Integer.parseInt(strArray[j])) > 0){
...

推荐阅读