簡體   English   中英

從“字符串”列表中找到所有數字,並將其相加,然后進行比較(如果等於)

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

我有一個頁面對象列表元素,稱為(number_Check)文本值=($ 479.00 / check)。 我有3個相同的值。 我需要添加它們並檢查它等於一個整數$ 1437.00 == finalnumber元素。 你可以幫幫我嗎? 我嘗試了正則表達式。 我不知道如何與最終數字進行比較。

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);
}

代碼有幾個問題,您不需要正則表達式即可。 這是一個簡單的版本。

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);

...並且由於您可能會大量重復使用此代碼,因此我編寫了一個函數,在去除了非數字后將字符串轉換為雙精度型。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM