简体   繁体   中英

Find all the numbers from the list String and add them and compare if it equals to

I have an page object list element called (number_Check) text value = ($479.00/check). I have 3 same values. I need to add them and check it equals to a full number $1437.00 == finalnumber element. Could you help me? I tried with regex. I don't know how to compare to final number.

List<String> mylist = new ArrayList<String>();

String regex = "-?[0-9]+(?:,[0-9]+)?";
Pattern p = Pattern.compile(regex);
for (int i = 0; i < number_check.size(); i++) {
    String bvalue = number_check.get(i).getAttribute("text");
    String cvalue = number_check.get(1).getAttribute("text");
    String dvalue = number_check.get(2).getAttribute("text");
    String final = finalnumber.getAttribute("text");
    Matcher m = p.matcher(bvalue);
    Matcher c = p.matcher(cvalue);
    Matcher d = p.matcher(dvalue);
    double sum = 0;
    while (m.find()) {
        mylist.add(m.group(0));
        mylist.add(c.group(0));
        mylist.add(d.group(0));
        sum += Double.parseDouble(m.group(0) + c.group(0) + d.group(0));
    }
    System.out.println(sum);
}

There are several problems with the code and you don't need regex to do this. Here's a simpler version.

double actual = 0;
for (int i = 0; i < number_check.size(); i++)
{
    actual += getDoubleFromString(number_check.get(i).getAttribute("text"));
}
double expected = getDoubleFromString(finalnumber.getAttribute("text"));

Assert.assertEquals(actual, expected);

...and since you are likely to reuse this a lot, I wrote a function to convert the string to a double after stripping out the non-numbers.

public static double getDoubleFromString(String s)
{
    return Double.parseDouble(s.replaceAll("[^\\d.]", ""));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM