有人可以告诉我如何删除以下代码输出列表中显示的$
字符吗?另外,我想在删除后添加所有元素的总和。请做好。
public static void HHDollarAmoutValidation(){
try{
int AAWithclientTablecount = webDriver.findElements(By.xpath("//*[@id='DataTables_Table_21']/tbody/tr")).size();
System.out.println(AAWithclientTablecount);
String[] options=new String[AAWithclientTablecount];
List<String> optionsList=null;
for (int i=1; i<=AAWithclientTablecount; i++)
{
options[i-1] = webDriver.findElement(By.xpath("//*[@id='DataTables_Table_21']/tbody/tr["+ i + "]/td[8]")).getText();
System.out.println(options[i-1]);
optionsList = Arrays.asList(options);
}
System.out.println(optionsList);
}
catch(Exception e){
System.out.println(e);
}
}
输出:
[$3,171,349.51, $0.00, $0.00, $0.00, $0.00, $0.00, $0.00, $0.00, $0.00, $0.00, $0.00, $0.00, $0.00, $0.00, $0.00, $0.00, $0.00, $0.00, $0.00]
答案 0 :(得分:0)
如果所有元素都有'$'作为第一个字符,只需更改此行即可删除它们:
options[i-1] = webDriver.findElement(By.xpath("//*[@id='DataTables_Table_21']/tbody/tr["+ i + "]/td[8]")).getText();
为:
options[i-1] = webDriver.findElement(By.xpath("//*[@id='DataTables_Table_21']/tbody/tr["+ i + "]/td[8]")).getText().substring(1);
要计算总和,请在将options
数组中的值插入的同时编码循环或添加值。
答案 1 :(得分:0)
从$
数组中删除options
,然后再将其添加到optionsList
:
options[i - 1] = options[i - 1].replace("$", ""); //add this line in the for loop
然后做总结。
注意:有很多选项可以做到这一点。
答案 2 :(得分:0)
您可以在List -
中实现以下逻辑public static void main(String[] args) {
List<String> l = new LinkedList<String>();
List<Double> r = new LinkedList<Double>();
l.add("$12");
l.add("$3.2");
l.add("$2.5");
l.add("4.5");
for (String s: l) {
if (s.startsWith("$")) {
s = s.substring(1);
r.add(new Double(s));
} else {
r.add(new Double(s));
}
}
System.out.println(r);
System.out.println(getSum(r));
}
private static Double getSum(List<Double> l) {
Double r = new Double(0);
for(Double d : l) {
r = r + d;
}
return r;
}
答案 3 :(得分:0)
工作代码:
public static void HHDollarAmoutValidation(){
try{
int AAWithclientTablecount = webDriver.findElements(By.xpath("//*[@id='DataTables_Table_21']/tbody/tr")).size();
System.out.println(AAWithclientTablecount);
String[] options=new String[AAWithclientTablecount];
List<String> optionsList=null;
for (int i=1; i<=AAWithclientTablecount; i++)
{
String Vstring = webDriver.findElement(By.xpath("//*[@id='DataTables_Table_21']/tbody/tr["+ i + "]/td[8]")).getText().replace(",", "").substring(1).trim();
System.out.println(Vstring+ " (at row: "+i+")");
sumIt = sumIt + Double.parseDouble(Vstring);
}
System.out.println(sumIt);
}
catch(Exception e){
System.out.println(e);
}
}