简单变换后分组
【问题】
The following transaction file content is the CSV file that contains financial transactions, where each line is either a debit or a credit transaction on a specific account number.
00001500205568600,D,1520.15
00001500205568600,D,12500.00
00001500205568600,C,44.00
00001300220978215,C,59800.13
00001300220978215,C,80000.00
00001300220978215,C,15850.23
00001300220978215,D,85.60
00002200540006410,D,595550.03
00002200540006410,C,1200.00
00002200540006410,D,3250.00
00001300220978215,C,12.55
00009650025500020,C,290050.00
00009650025500020,D,96.00
As you can see, each line has the following format:<account number>,<D or C; D for debit and C for credit>,<amount>
.
The file contains transactions for multiple account numbers, but more than one for each account number.
Write a Java program that reads the transactions.txt file line by line and calculates the final balance of each account number.
Assume that each account will start with 0 balance, the amount of each debit (D) transaction will be subtracted from the balance and the amount of each credit (C) transaction will be added to the balance.
The program should print each account number with its final balance.
I have this code and I need help in making transaction and print them.
public class Test1 {
public static void main(String[] args) {
test1 obj = new test1();
obj.run();
}
public void run() {
String csvFile = "transactions.txt";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
System.out.println("Account Number " + country[0]
+ " , Account Balance=" + country[2] + "]");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
【回答】
第2列等于D时,将第3列改为负数,然后进行简单的分组汇总即可。如无特殊要求,可用SPL实现,代码简单易懂:
A |
|
1 |
=file("d:\\source.csv").import@c() |
2 |
=A1.run(if(#2=="D",#3=-#3)) |
3 |
=A2.groups(#1;sum(#3)) |
A1:读取文件source.csv中的内容
A2:第2列等于D时,将第3列改为负数
A3:对第一列进行分组,并汇总第3列
上述代码很容易和JAVA集成,参考Java 如何调用 SPL 脚本。