java - 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
如何更正单双单元号的排序顺序。
解决方案
比较是在这一行进行的
if (strArray[i].compareTo(strArray[j]) > 0) {
...
为了将排序顺序从升序更改为降序,您只需更改>
为<
编辑
正如其他人评论的那样,为了按数值排序,您需要将字符串转换为数字。您可以通过将上述内容更改为:
if (Integer.compare(Integer.parseInt(strArray[i]), Integer.parseInt(strArray[j])) > 0){
...
推荐阅读
- php - 使用 REST api 更新记录
- python - ipywidgets 中选项的水平对齐
- c# - ASP.Net Core DI 公司上下文提供者?
- python - 如何在循环中为seaborn图表执行子图
- android - 为什么共享首选项不会在不同的语言环境中持续存在?
- c++ - 如何从 .docx 文件中获取数据并将其存储到剪贴板中?
- varnish - 如何将部分 URL 复制到重定向路径
- python - AttributeError: type object 'datetime.datetime' 没有属性 'datetime' 即使在使用 import datetime 之后
- javascript - 如何按主题标签过滤博客文章?
- pandas - 如何在 pandas DataFrame 中拆分包含嵌套数组的单元格