林創建其中用戶輸入nimber到文本框的GUI接口,數然後被加到作爲參數傳遞給CurrentAccount的對象。然後將該數字加上或減去一個隨機值。我希望這種情況每5秒發生一次,在公式完成後取值並加或減一個值,直到用戶告訴它停止。到目前爲止,我已經創建了這個代碼來決定是否應該添加一個隨機數字,生成隨機數字,將其添加或減去帳戶餘額,然後將帳戶餘額打印到文本字段。使用Thread.sleep代碼(5000)方法執行代碼每x秒
//method generates a random number to determine if a value should be added or subtracted from the myBalance variable within theAccount classes and completes the equation
int month = 0;
private void simulate()
{
try
{
if(month<12)
{ //Creates instance of Random to decide if the random number should be added or subtracted to the balance
Random decider = new Random();
for (int i = 0; i < 1; i++)
{
int ans = decider.nextInt(2)+1;
//if the decider value == 1, subtract or "withdraw" random number from the balance
if (ans == 1)
{
//creates instance of Random to create random number
Random bal = new Random();
int withdrawAmount = bal.nextInt((500 - 100) + 1) + 100;
//sets account balance to the balance subtract the random number
theAccount.myBalance = theAccount.myBalance - withdrawAmount;
//increments the month timer
month++;
//prints the new balance to the transaction text field
jTextArea2.setText("The new balance is " + theAccount.myBalance);
} else
{
//if decider value == 2, add or "deposit" random number to the balance
//creates instance of Random to create random number
Random bal = new Random();
int depositAmount = bal.nextInt((500 - 100) +1) + 100;
//sets account balance to the balance plus the random number
theAccount.myBalance= theAccount.myBalance + depositAmount;
//increments the month timer
month++;
//prints the new balance to the transaction text field
jTextArea2.setText("The new balance is " + theAccount.myBalance);
}
//if the account has a balance of -£200, generate an error and reset the balance to the user inputted value
if (theAccount.myBalance < -200)
{
jTextArea1.setText("Overdraft of £200 only");
theAccount.myBalance = value;
}
//if the account has a balance of 0, generate an error as the account must always have at least £1 before entering the overdraft
if(theAccount.myBalance == 0)
{
jTextArea1.setText("An account must always have £1");
}
}
}
} catch (NullPointerException i)
{
jTextArea2.setText("Create an Account");
}
}
香港專業教育學院嘗試,但必須把它放在錯誤的地方,因爲它停留5秒的創建按鈕,並打印出自身的平衡。任何關於這件事的幫助都會很大。另外我有一個方法來檢測用戶輸入,顯然是一個按鈕上的動作監聽器來調用它和這個方法。
[修改後的評論] 我也嘗試過使用一個計時器來循環代碼,但我似乎無法得到它指向正確的代碼重複,因爲它只是沒有做任何事情,而不是填滿內存。
ActionListener timerListener = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
ControlPanel.this.simulate();
}
};
Timer theTimer = new Timer(5000,timerListener);
看看'java.swing.util.Timer'。它可以爲GUI線程定期安排任務。 http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer。html – markspace
謝謝你,我試過一個計時器,我會修改我的評論以顯示我的代碼,我的問題是它沒有被調用,所以我顯然沒有把它指向正確的代碼 – brushbrushbrush