select java 中的逗号分隔值中的每个值

select each value in comma-separated values in java

这是我的代码和结果

我想要的是计算每个账号的总余额,我如何select区分每个账号和它的余额来做运算(减法和加法)?

结果如下: 账号,D为借方,C为贷方,Balance

对于您读入的每一行,您可以在逗号符号上拆分字符串,例如

String[] transactionLineElements = transactionLine.split(",");

这将为您提供一个字符串数组,其中第 3 个元素(在索引 2 处)是交易 value/balance - 即 transactionLineElements[2]。然后您可以将该交易值字符串解释为数字,例如

BigDecimal balance = new BigDecimal(transactionLineElements[2]);

同样可以解析账号,例如:

Long accountNumber = Long.valueOf(transactionLineElements[0]);

您必须使用逗号分隔值,使用 String.split(String regex)。例如:

String[] values = transactionLine.split(",");  // it can be a regex too
// You should check values.length for if there are less/more values than needed

如果你的数字很大就用Long.parseLong(String s) to parse the account number into a long. You might want to use BigInteger.valueOf(String s)代替

long accountNumber = Long.parseLong(values[0]);
// Or use this instead:
BigInteger accountNumber = BigInteger.valueOf(values[0]);

要检查它是贷方还是借方,请记住您必须使用 String.equals(String s) 来比较字符串内容,千万不要使用 ==:

if (values[1].equals("D")) {
    // debit
}
else if (values[1].equals("C") {
    // credit
}
else {
    // wrong input; you should tell the user here
}