混淆了递归方法&循环

时间:2015-06-23 13:00:12

标签: java for-loop recursion methods

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

即使引脚不正确,该程序也会在Main类中执行下一个方法。

主要思想是当你的引脚正确时,方法将完成,程序转到下一个方法。如果PIN不正确,则会有3次。如果所有的努力都是错误的,那么该计划就会消失。因此,您的卡将被阻止。请给我一个平静的建议。

#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>

int main( int argc, char *argv[] )
{
    int sockfd, streamfd, addr_size, status;
    char buffer[256];
    struct sockaddr_in serv_addr, cli_addr;
    struct in_addr **addr_list;

    struct hostent *hptr;
    char  *ptr, **pptr;
    char  str[32];
    sockfd = socket(PF_INET, SOCK_STREAM, 0);

    if (sockfd < 0)
    {   
       perror("ERROR opening socket");
       exit(1);
    }

   /* Initialize socket structure */
   bzero((char *) &serv_addr, sizeof(serv_addr));

   serv_addr.sin_family = PF_INET;
   serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
   serv_addr.sin_port = htons(1234);

  /* Now bind the host address using bind() call.*/
  if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
  {
  perror("ERROR on binding");
  exit(1);
  }

  /* Now start listening for the clients, here process will
   * go in sleep mode and will wait for the incoming connection
  */

  listen(sockfd,10);
  addr_size = sizeof(cli_addr);

  /* Accept actual connection from the client */
  while(1){
       streamfd = accept (sockfd, (struct sockaddr *) &cli_addr, &addr_size);   

       status = read (streamfd, buffer, 255);   
       printf ("string from net: %s\n", buffer);



       if((hptr = gethostbyname(buffer)) == NULL)
       {
           printf("gethostbyname error for host:%s\n", buffer);
           return 0; 
       }



       printf("IP Address:%s\n",inet_ntoa(*((struct in_addr *)hptr->h_addr)));
       close(streamfd); 
    }
    return 0;
}

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

5 个答案:

答案 0 :(得分:5)

首先,循环的条件应该是i&gt; 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;
}

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

答案 1 :(得分:2)

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

因为您试图递归输入引脚直到用户输入正确的内容...然后authenticity将始终返回true或继续无休止地

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

如果您没有再尝试,我将返回false,否则将获得一个新的针脚并检查是否正确... 如果数字不正确,则递归调用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,因为它根本没有多大意义..

答案 2 :(得分:1)

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;如果你想要更多,那么使用更多

答案 3 :(得分:0)

看起来你错过了递归的一些关键步骤。在这种情况下,使用简单的迭代而不是递归可能会更好,并且可以更好地组织代码。不清楚你的扫描仪是否是另一种方法或字段中的局部变量,并且你的递归是错误的,因为它在调用自身时从未通过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
       }
   }
}

答案 4 :(得分:0)

运行代码的工作方式。假设你修复了循环。

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;
  }