【问题标题】:How to run 2 times of do-while loop only?如何只运行 2 次 do-while 循环?
【发布时间】:2011-11-10 16:20:29
【问题描述】:

如何修改下面的密码,使用户只能输入2次错误的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);

【问题讨论】:

  • 呃。在do{ 循环开始时添加一个计数器怎么样?它有类似if (++counter > 2) { get angry... }

标签: java loops do-while


【解决方案1】:

您只需要添加一个计数器,以计算用户尝试输入 pin 的次数,然后验证您的 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);
 }

【讨论】:

  • 如果 MAX_INCORRECT_PIN_THRESHOLD = 2;尝试 = 0;总错误时间可以是 3
  • 抱歉,应该是attempts &lt; MAX_INCORRECT_PIN_THRESHOLD,而不是attempts &lt;= MAX_INCORRECT_PIN_THRESHOLD。我已经相应地更新了答案。
  • 好的,感谢您的帮助,因为我是编程初学者~非常感谢~
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    int counter = 0;
     do
        { if(counter++ >= 2){ break;}
            String pin2String = JOptionPane.showInputDialog("Enter PIN");
            pin2 = Integer.parseInt(pin2String);
        }while(pin2 != pin);
    

    【讨论】:

      【解决方案4】:

      在其中放置一个简单的计数器,在两次迭代后终止循环,然后在离开循环后检查 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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-02
        • 1970-01-01
        • 2020-04-29
        • 1970-01-01
        • 2016-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多