2015-02-11 149 views
-1

試圖顯示一條錯誤消息,以便當用戶輸入pin不正確三次時,它將顯示錯誤消息「account blocked」。爲什麼pinAttempts ++在每次輸入不正確的引腳時都不加1?count ++在if語句中不起作用

try { 
    int pinAttempts = 0; 
    int pin = Integer.parseInt(enterPinJTextField.getText()); 
    if (pinAttempts == 3) { 
     JOptionPane.showMessageDialog(popupFrame, "Account blocked!"); 
    } 
    if (pin != PIN) { 
     pinAttempts++; 
     JOptionPane.showMessageDialog(popupFrame, "Please enter correct pin!"); 
    } else { 
     BankAccount application = new BankAccount(); 
     application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 
} catch (NumberFormatException exception) { 
    JOptionPane.showMessageDialog(popupFrame, "Please enter a number"); 
} 
+0

1 )不要使pinAttempts = 0;如果每次用戶按回車時調用它,都將進入try {}。 2)如果(pinAttempts == 3){...把一個返回;返回並且不執行其他代碼} – crAlexander 2015-02-11 20:39:14

+0

@Kelv如果其中一個答案適合您,請考慮接受它。 – 2015-02-12 14:02:58

回答

5

,因爲你又

int pinAttempts = 0; 
4

將其設置爲0您輸入您設置pinAttempts try語句爲0。每當這意味着不管它是什麼之前,將被覆蓋。

您應該將pintAttempts = 0移動到發生初始化的地方,以便它只發生一次。或者在可以重置用戶嘗試計數器的方法中使用它。

1

爲什麼pinAttempts ++在每次輸入不正確的引腳 時都不加1?

這是不用擔心,這是你的理解是錯誤的。

你需要認識到,你每次都重新初始化pinAttempts 0重新進入使用

int pinAttempts = 0;在開始try塊。

聲明全局變量(在類的頂部)而不是在try/catch塊中聲明變量,它將起作用。

0

問題是,pinAttempts是越來越一次又一次的初始化值0

讓您pinAttempts靜態或聲明它某處,它不會被一次又一次的初始化,我會做這樣的事情。

static int pinAttempts=0; 
public boolean isLoginSuccessfull(){ 

//here do whatever you want to do . 

} 

此登錄全成將被稱爲每當用戶試圖登錄,所以pinAttempts將不會再初始化,只要你決定疏通用戶做出再次pinAttempts計數0