【问题标题】:Confused with recursive methods & loops对递归方法和循环感到困惑
【发布时间】:2015-09-09 07:04:59
【问题描述】:

我写了下面的方法,但它不能正常工作。

即使 pin 不正确,这个程序也会执行 Main 类中的 next 方法。

主要思想是当您的引脚正确时,方法将完成并且程序转到下一个方法。如果 PIN 不正确,您将有 3 次。如果所有的努力都错了,那么程序就会失败。因此,您的卡将被冻结。请给我一个平静的建议。

public boolean authenticity(short pin)  {
       if (pin == 1234) {
           System.out.println("PIN is correct");
           System.out.println("Card is active for operation!");
           return true;
       } else {
           pin = sc.nextShort();
           for (int i = 1; i >= 3; i++) {
               System.out.println("PIN isn't correct! You have " +i +"effort(s)");
               return authenticity(pin);  // recursion
           }
       }
       return false;
  }

*在Main类中,方法根据命令执行: 真实性(sc.nextShort());

【问题讨论】:

  • 你能说明你在哪里声明sc吗?
  • for (int i = 3; i <0; i--) 你的循环应该有i > 0
  • 我觉得这个问题的题目应该改一下。它没有太多关于布尔方法的内容,而是递归和循环的诚实错误。
  • 在我的例子中,我解释了 "sc" @private final static Sc​​anner sc = new Scanner(System.in);
  • 我也做了一些更正,因为我弄错了,我使用的是旧版本的程序。我的道歉! @ for (int i = 1; i >= 3; i++)

标签: java for-loop recursion methods


【解决方案1】:

你的方法没有多大意义……

因为您正在尝试递归输入 pin,直到用户输入正确...然后 authenticity 将始终返回 true 或继续无休止

以下是代码的工作原理... 在返回false之前,您需要调用authenticity方法传递重试次数。

如果你没有更多的尝试,我将返回false,否则获取一个新的 pin 并检查正确性...... 如果数字不正确,则递归调用 authenticity 将重试次数减一...

authenticity(3); // call the method passing 3 as max number of tries...

public static boolean authenticity(int tries) {
          if (tries > 0)
          {
           short pin = sc.nextShort();
           if (pin == 1234) {
               System.out.println("PIN is correct");
               System.out.println("Card is active for operation!");
               return true;
           } else {
               System.out.println("PIN isn't correct! You have " + tries +"effort(s)");
               return authenticity(--tries); 
           }
          } 
          return false;
      }

我删除了for,因为它根本没有多大意义..

【讨论】:

  • 这是一个糟糕的答案。您的递归没有中断条件。 OPs 问题中的代码意图只允许 3 次重试。
  • 你说得对...我误解了代码...我编辑了自己的代码以符合要求...
  • 如何更好地实现中断条件?我有两个想法:try-catch 结构的例外或匿名实习生类......你的意见是什么?
【解决方案2】:

您似乎缺少一些递归的关键步骤。在这种情况下,使用简单的迭代而不是递归可能会更好,并且更好地组织您的代码。目前尚不清楚您的扫描仪等是否是另一个方法或字段中的局部变量,并且您的递归是错误的,因为它在调用自身时从未通过i(字段)。

您似乎在代码的不同部分对同一事物进行了一些扫描读取,出于组织原因,这一切都应该发生在同一个地方:

public boolean authenticateUser(Scanner sc) {
   for(int tries = 0; tries<3; tries++){
       short attempt = sc.nextShort();
       if(attempt==1234) return true;
   }
   return false;
}

如果你还想使用递归:

public boolean authenticateUser(short pin, int triesLeft) {
   if(triesLeft==0){
       System.out.println("You are out of tries.");
       return false;
   }
   if (pin == 1234) {
       System.out.println("PIN is correct");
       System.out.println("Card is active for operation!");
       return true;
   } else {
       pin = sc.nextShort();
       System.out.println("PIN isn't correct! You have " +i +"effort(s)");
       return authenticity(pin, triesLeft-1);  //it's recurcy
       }
   }
}

【讨论】:

    【解决方案3】:

    首先,循环的条件应该是 i > 0 :

           for (int i = 3; i > 0; i--) {
               System.out.println("PIN isn't correct! You have " +i +"effort(s)");
               return authenticity(pin);  
           }
    

    其次,在您当前的实现中,每个递归调用都会给用户 3 次额外尝试(至少在出现 StackOverflow 之前)。您应该将剩余尝试次数作为参数传递给递归调用。而且你不需要循环。

    public boolean authenticity(short pin, int remainingAttempts) {
        if (pin == 1234) {
            System.out.println("PIN is correct");
            System.out.println("Card is active for operation!");
            return true;
        } else {
            pin = sc.nextShort();
            remainingAttempts--;
            if (remainingAttempts > 0) {
                System.out.println("PIN isn't correct! You have " +remainingAttempts +" attempts left");
                return authenticity(pin,remainingAttempts);
            }
        }
        return false;
    }
    

    如果你想保持循环,你可以摆脱递归。

    【讨论】:

    • 另外,摆脱循环。
    • @mlk 是的,我自己才意识到。
    【解决方案4】:

    了解代码的工作原理。假设您修复了循环。

    authenticity(1):
    
    public boolean authenticity(short pin) `{`
           if (pin == 1234) { // 1 == 1234 == FALSE
               System.out.println("PIN is correct");
               System.out.println("Card is active for operation!");
               return true;
           } else { // PASS
               pin = sc.nextShort(); // USER GETS TO TYPE SOMETHING NEW. Lets say "2"
               for (int i = 3; i > 0; i--) { // EXECUTES THE FOLLOWING THREE TIMES
               System.out.println("PIN isn't correct! You have " +i +"effort(s)"); // What does this print? Why?
               return authenticity(pin);  // EXCEPT RETURNS ON THE FIRST LOOP
               }
           }
           return false;
      }
    
    
    authenticity(1):
      authenticity(2): 
    
    public boolean authenticity(short pin) `{`
           if (pin == 1234) { // 2 == 1234 == FALSE
               System.out.println("PIN is correct");
               System.out.println("Card is active for operation!");
               return true;
           } else { // PASS
               pin = sc.nextShort(); // USER GETS TO TYPE SOMETHING NEW. Lets say "3"
               for (int i = 3; i > 0; i--) { // EXECUTES THE FOLLOWING THREE TIMES
               System.out.println("PIN isn't correct! You have " +i +"effort(s)"); // What does this print? Why?
               return authenticity(pin);  // EXCEPT RETURNS ON THE FIRST LOOP
               }
           }
           return false;
      }
    
    authenticity(1):
      authenticity(2): 
        authenticity(3): 
    
    public boolean authenticity(short pin) `{`
           if (pin == 1234) { // 3 == 1234 == FALSE
               System.out.println("PIN is correct");
               System.out.println("Card is active for operation!");
               return true;
           } else { // PASS
               pin = sc.nextShort(); // USER GETS TO TYPE SOMETHING NEW. Lets say "4"
               for (int i = 3; i > 0; i--) { // EXECUTES THE FOLLOWING THREE TIMES
               System.out.println("PIN isn't correct! You have " +i +"effort(s)"); // What does this print? Why?
               return authenticity(pin);  // EXCEPT RETURNS ON THE FIRST LOOP
               }
           }
           return false;
      }
    
    authenticity(1):
      authenticity(2): 
        authenticity(3): 
           authenticity(4): 
    
    public boolean authenticity(short pin) `{`
           if (pin == 1234) { // 4 == 1234 == FALSE
               System.out.println("PIN is correct");
               System.out.println("Card is active for operation!");
               return true;
           } else { // PASS
               pin = sc.nextShort(); // USER GETS TO TYPE SOMETHING NEW. Lets say "5"
               for (int i = 3; i > 0; i--) { // EXECUTES THE FOLLOWING THREE TIMES
               System.out.println("PIN isn't correct! You have " +i +"effort(s)"); // What does this print? Why?
               return authenticity(pin);  // EXCEPT RETURNS ON THE FIRST LOOP
               }
           }
           return false;
      }
    

    【讨论】:

      【解决方案5】:
      public boolean authenticity(short pin, int tried) {
          if (pin == 1234) {
              System.out.println("PIN is correct");
              System.out.println("Card is active for operation!");
              return true;
          } else {
              pin = sc.nextShort();
              System.out.println("PIN isn't correct! You have " +tried +"effort(s)");
              if(tried==0)
                  return false;
              return authenticity(pin,--tried);
          }
          return false;
      }
      

      使用tried == 3;如果你想要更多,那就使用更多

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-14
        • 2018-10-03
        • 2013-05-15
        • 2013-07-27
        • 1970-01-01
        • 2016-07-13
        • 2017-05-03
        • 1970-01-01
        相关资源
        最近更新 更多