我正在做一个简单的事务项目,这是我第一次用Java编写,所以这是代码片段:
private static void loadHistory(List<Transaction> transactions) {
double totalDebitCount = calculateTotalCountByType(transactions, TransactionType.DEBIT);
double totalCreditCount = calculateTotalCountByType(transactions, TransactionType.CREDIT);
System.out.println("There are " + totalCreditCount + "transactions in the database");
System.out.println();
for (Transaction transaction : transactions) {
System.out.println(transaction.toString());
}
System.out.println();
System.out.println("Total count for all debit transactions is" + totalDebitCount);
System.out.println("Total count for all credit transactions is " + totalCreditCount);
}
和第二个:
public static double calculateTotalCountByType(List<Transaction> transactions, TransactionType type) {
double total = 0;
for (Transaction transaction : transactions) {
if (transaction.type == type) {
total = total + transaction.quantity * transaction.exchangeRate;
}
}
return total;
}
顺便说一下,我根本不需要exchangeRate*数量,所以可以直接删掉
您的代码当前计算和交易金额
total = total + transaction.quantity; // Ignoring exchange rate
如果你想要的是计数,这应该是
total = total + 1
,返回值应该是int
,而不是double
。
旁注:永远不要在财务金额中使用浮点数。浮点数在某些操作中会失去精度。始终使用无损格式,如BigDecimal
。