【问题标题】:Calling method within itself在自身内部调用方法
【发布时间】:2018-01-12 07:25:33
【问题描述】:

我想做一个输入,它接受 1 - 10 的数字并打印范围。

我需要检查输入是否为整数(检查),检查范围是否为 0-10(检查),如果不是这些,请再次询问用户。那么,递归方法?

目前我有这个:

import java.util.Scanner; 
import java.util.InputMismatchException; 

public class FinalTest {
  public static void main (String [] args) {

    Scanner in = new Scanner(System.in);
    int k = 0;

    System.out.print("int - ");

    try {
      k = in.nextInt();
    } catch (InputMismatchException e) {
      System.out.println("ERR: Input");
      System.exit(1);
    }

    if(k <= 10 && k > 0) {
      for(int j=1; j <= k; j++) {
        System.out.println(j);
      }
    } else {
      System.out.println("ERR: Oob");
      System.exit(1);
    }
  }
}

我想替换“System.exit()”,以便它再次尝试要求用户输入。

调用main(); 会产生错误。

这种情况下如何正确调用main方法?

【问题讨论】:

  • 我建议一个循环。
  • 你不需要递归。只需使用一个循环。见:The while and do-while Statements
  • 把它粘在一个循环里。或者将逻辑放入一个函数中并递归调用该函数。
  • 为了它的价值,你可以使用递归方法,但你不应该这样做。一个简单的循环就足够了while(don't have valid answer){ask for answer}
  • 是循环它:While(不正确){}

标签: java loops recursion methods


【解决方案1】:

这里有两个选择:

  • 实际创建一个方法并调用它
  • 只需使用循环

循环可能是这样的:

boolean askForInput = true;
while ( askForInput ) {
  try {
    k = in.nextInt();
    askForInput = false;
  } catch ...
    print "not a number try again"
}

但除此之外:您仍然希望将此代码放入它自己的方法中。不是因为该代码应该调用自己,而是为了清楚起见。喜欢:

public static int askForNumber(Scanner in) {
  ... code from above
  return k;
}

回答你的问题:你不想在这里使用递归。你想循环;是的,recursion 是实现循环的一种方法,但考虑到您要在此处实现的要求,这简直是矫枉过正。

记录一下:在创建该辅助方法时,您实际上可以将其简化为:

public static int askForNumber() {
  while ( askForInput ) {
    try ...
      return in.nextInt();
    } catch ...
    print "not a number try again"
  }
}

除此之外:您通常将递归用于计算 任务,例如计算阶乘或斐波那契数……例如,请参阅here

【讨论】:

  • 嘿,感谢您的回答。非常有帮助。只有一件事 - 为什么这不起作用? boolean askForInput = true; while ( askForInput ) { System.out.print("int - "); try { k = in.nextInt(); askForInput = false; } catch (InputMismatchException e) { System.out.println("ERR: Input"); } }
  • 它只是继续打印 ERR。它不应该每次都提示输入吗?下面是 pastebin 网址,方便阅读:pastebin.com/vPrXw3MX
  • @py9 我点击该链接并将其放入一个简单的 main 方法中......它打印“int-”......我输入一个数字,按回车......程序结束。因此:请在此处添加minimal reproducible example - 我可以作为一个整体下载并运行以重现问题。
  • 问题在于您输入的不是整数而是字符串。它不应该转到循环的开头并再次要求输入吗? (因为 askForInput 仍然为真)。以下是完整代码:pastebin.com/GAykyrwj
  • @py9 好的。我不得不承认我只是对 nextInt() 的工作原理有一个错误的理解。因此,您可能希望使用之前的 try/catch 代码。老实说,我今天很忙,自己开始用那台扫描仪做实验。
【解决方案2】:

对于递归方法打印范围的部分:

public void printAscending(int n) {
  if (n > 0) {
     printAscending(n - 1);
     System.out.println(n);
  }
}

【讨论】:

    【解决方案3】:

    我认为使用递归对于简单的事情来说太过分了,而且可能会更昂贵。您可以在扫描位周围添加一个 while 循环,直到输入的值有效。我还将打印循环置于 while 之外,这样就不必在打印之前测试条件,因为如果您退出 while 循环,则意味着数字(如果有效)。您可以只测试 -1 值以退出进程。

    public class FinalTest
    {
        public static void main (String [] args)
        {
            Scanner in = new Scanner(System.in);
            int k = 0;
    
            do
            {
                System.out.print("int - ");
    
                try
                {
                    k = in.nextInt();
                }
                catch (InputMismatchException e)
                {
                    System.out.println("ERR: Input");
                    System.exit(1);
                }
            }
            while(!(k>0 && k<=10) && k!=-1);
    
            if(k!=-1)
            {
                for(int j=1; j<=k; j++)
                {
                    System.out.println(j);
                }
            }
            else
            {
                System.out.println("Bye Bye.");
            }
        }
    }
    

    【讨论】:

      【解决方案4】:

      好的,所以当我需要使用递归时,我个人会为它创建一个单独的函数/方法。当我需要重新启动该方法时,我只是在其内部调用它。所以它会是这样的:

      private void recursiveMethod() {
      // do stuff . . .
      if (yourCondition) {
          //continue to next piece of code
      } else {
          recursiveMethod();
      }
      

      }

      但在大型项目中,尽量远离递归,因为如果你搞砸了,它可以

      【讨论】:

        猜你喜欢
        • 2016-06-10
        • 1970-01-01
        • 1970-01-01
        • 2020-11-04
        • 1970-01-01
        • 2010-12-09
        • 2022-11-21
        • 2011-11-14
        相关资源
        最近更新 更多