如何只运行2次do-while循环?

时间:2011-11-10 16:20:29

标签: java loops do-while

如何修改下面的代码成为用户只能输入2次错误的PIN码?错误的PIN输入2次后,程序将自动退出。

    String user = "Melissa";
    int pin = 123456;
    int pin2;

    // Prompt the user for input
    do
    {
        String pin2String = JOptionPane.showInputDialog("Enter PIN");
        pin2 = Integer.parseInt(pin2String);
    }while(pin2 != pin);

    // Display
    JOptionPane.showMessageDialog(null, "User: "+ user);

4 个答案:

答案 0 :(得分:4)

您只需添加一个计数器,计算用户尝试输入引脚的次数,然后验证while循环条件下的条件。

例如:

 String user = "Melissa";
 int pin = 123456;
 int pin2;
 int MAX_INCORRECT_PIN_THRESHOLD = 2;
 int attempts = 0;

 // Prompt the user for input
 do {
     String pin2String = JOptionPane.showInputDialog("Enter PIN");
     pin2 = Integer.parseInt(pin2String);
     attempts++;
 } while(pin2 != pin && attempts < MAX_INCORRECT_PIN_THRESHOLD);

 if (pin2 == pin) {
     // Display
     JOptionPane.showMessageDialog(null, "User: "+ user);
 }

答案 1 :(得分:0)

int counter = 0;
 do
    { if(counter++ >= 2){ break;}
        String pin2String = JOptionPane.showInputDialog("Enter PIN");
        pin2 = Integer.parseInt(pin2String);
    }while(pin2 != pin);

答案 2 :(得分:0)

尝试一个只循环两次的for循环。那可能会更容易。

VALID:
for(int i= 0; i < 2; i++){
  if(pin==pin2){
    //Valid login...
    break VALID;
  }else if(i == 1){
   System.exit(0);
  }
}

答案 3 :(得分:0)

在那里放一个简单的计数器,在两次迭代后终止循环,然后在离开循环后检查PIN是否无效:

String user = "Melissa";
int pin = 123456;
int pin2;
int count = 0;

// Prompt the user for input
do
{
    String pin2String = JOptionPane.showInputDialog("Enter PIN");
    pin2 = Integer.parseInt(pin2String);
}while(pin2 != pin && count++ < 2);

if(pin2 != pin)
{
  // Kansas is going bye-bye - call exit logic
}

// Display
JOptionPane.showMessageDialog(null, "User: "+ user);