0
Ich habe diesen JUnit-Test erstellt, um zu testen, wie alle Werte von Objekten mit dem Wert BigDecimal berechnet werden.So berechnen Sie BigDecimal
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Test;
public class BigDecimalTest
{
private BigDecimal sumAmounts(List<ExpressCheckout> myList)
{
BigDecimal total = new BigDecimal(BigInteger.ZERO);
for (ExpressCheckout item : myList)
{
total.add(item.getAmount());
}
return total;
}
@Test
public void testBigDecimalTest()
{
try
{
List<ExpressCheckout> list = new ArrayList<>();
for (int i = 0; i < 12; i++)
{
ExpressCheckout obj = new ExpressCheckout();
obj.setCurrency("USD");
Random rand = new Random();
int n = rand.nextInt(50) + 1;
obj.setAmount(new BigDecimal(n));
obj.setQuantity(1);
obj.setName("test name");
obj.setDescription("test description");
list.add(obj);
}
BigDecimal sumAmounts = sumAmounts(list);
System.out.println(">>>>>>>>>>>>>>>>>>>> sumAmounts " + sumAmounts.toString());
}
catch (Exception ex)
{
Logger.getLogger(BigDecimalTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public class ExpressCheckout
{
String currency;
BigDecimal amount;
int quantity;
String name;
String description;
public ExpressCheckout()
{
}
public ExpressCheckout(String currency, BigDecimal amount, int quantity, String name, String description)
{
this.currency = currency;
this.amount = amount;
this.quantity = quantity;
this.name = name;
this.description = description;
}
public String getCurrency()
{
return currency;
}
public void setCurrency(String currency)
{
this.currency = currency;
}
public BigDecimal getAmount()
{
return amount;
}
public void setAmount(BigDecimal amount)
{
this.amount = amount;
}
public int getQuantity()
{
return quantity;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
}
}
Aus irgendeinem Grund sumAmounts 0
ich Folge bekommen eine Ahnung, warum ich dieses Ergebnis zu erhalten, und wie ich es beheben kann? Das Ergebnis sollte aus allen BigDecimal-Werten aus der Java-Liste berechnet werden.
Statt 'BigDecimal total = new BigDecimal (BigInteger.ZERO) ; 'write ist wie folgt:' BigDecimal total = BigDecimal.ZERO; '... Es muss nicht jedes Mal ein neues Objekt erstellt werden, eins für Null existiert bereits. –