Java 如何制作历史任务算法?
我有一个银行账户,在那里我执行诸如:存款/取款等任务。我需要创建历史记录,其中存储了我最后做的10个动作。(假设整个银行只有一个账户) 我认为,至少有两类:银行账户和行动Java 如何制作历史任务算法?,java,Java,我有一个银行账户,在那里我执行诸如:存款/取款等任务。我需要创建历史记录,其中存储了我最后做的10个动作。(假设整个银行只有一个账户) 我认为,至少有两类:银行账户和行动 class BankAccount { private Action performTask; public class Action() { private int actIndex; private String[] act = new String[10]; Ac
class BankAccount {
private Action performTask;
public class Action() {
private int actIndex;
private String[] act = new String[10];
Action() {
actIndex = -1;
}
public void add(String title) {
++actIndex;
act[actIndex] = title;
}
}
public void deposit(){
performTask.add("Deposit");
}
}
可能会有错误,但仍然没有得到预期的结果。我怎样才能达到我想要的结果?有什么想法吗?嗯,只是个想法
您可以维护大小为10的队列
执行取款和存款操作的位置,对队列进行更改以反映最近的操作。操作
类是抽象类。它有两个功能:
doAction(int k)
根据实现进行取款或存款
printAction()
用于打印执行的操作
存款操作
和取款操作
是Action
类的两个实现
actionList
是一个队列
,它保存最近发生的10个事务
amount
是活期账户持有的总金额,这是两个类存款操作
和取款操作
的编号
希望这对你有帮助
public class BankAccount{
private int amount;
private Queue<Action> actionList=new LinkedList<Action>();
public void withDraw(int k){
Action a = new withdrawAction();
a.doAction(k);
if(actionList.size()<10){
actionList.offer(a);
}
else{
actionList.poll();
actionList.offer(a);
}
}
public void deposit(int k){
Action a = new DepositAction();
a.doAction(k);
if(actionList.size()<10){
actionList.offer(a);
}
else{
actionList.poll();
actionList.offer(a);
}
}
abstract class Action{
String actionDesc=null;
abstract void doAction(int k);
abstract void printAction();
}
class DepositAction extends Action{
@Override
void doAction(int k) {
amount=amount+k;
actionDesc="Deposit: "+k;
}
@Override
void printAction() {
System.out.println(actionDesc);
}
}
class withdrawAction extends Action{
@Override
void doAction(int k) {
if(amount-k<0){
throw new IllegalArgumentException();
}
amount=amount-k;
actionDesc="Withdraw: "+k;
}
@Override
void printAction() {
System.out.println(actionDesc);
}
}
}
公共类银行账户{
私人整数金额;
private Queue actionList=新建LinkedList();
公开作废撤销(int k){
动作a=新动作();
a、 doAction(k);
如果(actionList.size()1)没有像您当前所做的那样嵌套这些类。2)如果可能的话,我会将Action作为一个接口。我现在正在使用嵌套类,练习是在这种情况下使用它。编辑:也许我需要通过创建aAction的对象来实现这一点?并在我的银行帐户类中初始化Action lastAct。(?)那么,您期望的结果是什么?实际结果是什么?不,我需要实现使用嵌套类创建最后10个任务历史的算法。(在我的帖子中,这只是我的想法中的一个结构)@Ernusc I给出了一个使用队列的示例,但如果您希望最后10个操作按最新操作的顺序进行……您可以使用堆栈,方式相同。等待您的反馈。