2015-02-11 123 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