Steven_Tian
unread,Dec 5, 2010, 6:05:20 PM12/5/10Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Good Ideas
import java.text.DecimalFormat;
import java.util.*;
import java.io.*;
public class StockTransaction {
public static void main(String[] args) {
File src = new File(
"D:\\ProgramFiles\\eclipse\\test\\src\\trans.txt");
LinkedList ll = new LinkedList();
try {
FileInputStream f = new FileInputStream(src);
BufferedReader br = new BufferedReader(new InputStreamReader(f));
String record = br.readLine();
while (record != null) {
String[] strs = new String[record.length()];
strs = record.split(",");
TransactionRecord tr = new TransactionRecord();
tr.setbOrs(strs[0]);
tr.setUnit(Integer.parseInt(strs[1]));
tr.setPrice(Float.parseFloat(strs[2]));
ll.add(tr);
record = br.readLine();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
float cost = 0f, sum = 0f;
LinkedList lb = new LinkedList();
LinkedList ls = new LinkedList();
for (int i = 0; i < ll.size(); i++) {
TransactionRecord tr = (TransactionRecord) ll.get(i);
if (tr.getbOrs().equalsIgnoreCase("B")) {
cost += tr.getPrice() * tr.getUnit();
lb.add(tr);
} else if (tr.getbOrs().equalsIgnoreCase("S")) {
ls.add(tr);
}
}
for (int i = 0; i < ls.size(); i++) {
TransactionRecord tr = (TransactionRecord) ls.get(i);
for (int j = 0; j < lb.size(); j++) {
TransactionRecord trForS = ((TransactionRecord) ll.get(j));
if (tr.getUnit() > trForS.getUnit()) {
sum += trForS.getUnit()
* (tr.getPrice() - trForS.getPrice());
tr.setUnit(tr.getUnit() - trForS.getUnit());
trForS.setUnit(0);
} else if (tr.getUnit() < trForS.getUnit()) {
sum += tr.getUnit() * (tr.getPrice() - trForS.getPrice());
trForS.setUnit(trForS.getUnit() - tr.getUnit());
tr.setUnit(0);
} else {
sum += tr.getUnit() * (tr.getPrice() - trForS.getPrice());
}
}
}
DecimalFormat twoDForm = new DecimalFormat("#.##");
System.out.print("報酬率 = "
+ String.valueOf(twoDForm.format((sum / cost) * 100)) + "%");
}
}
class TransactionRecord {
String bOrs;
int unit;
float price;
public String getbOrs() {
return bOrs;
}
public void setbOrs(String bOrs) {
this.bOrs = bOrs;
}
public int getUnit() {
return unit;
}
public void setUnit(int unit) {
this.unit = unit;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
-------------------------------
trans.txt format
前後不可有空白
-------------------------------
B,10,12.5
B,80,11
S,20,15
B,30,9
S,70,18