【问题标题】:How to print numbers from 1 to n using recrsion in java如何在java中使用递归打印从1到n的数字
【发布时间】:2022-01-13 03:35:27
【问题描述】:
public static void increase(int N){
    int a = 1;

    if(b <= N) {
        System.out.print(a + " ");
        a++;
    } else {
        increase(N);                
    }
}

我可以看到这种方法的问题,即每次代码进行递归调用时,int a 都会初始化为1。谁能提出正确的解决方案?

【问题讨论】:

  • a 作为参数传递给increase

标签: java recursion


【解决方案1】:
  public static void main(String[] args) {
        increase(10,1);
    }
    private static  void increase(int N,int begin){

        if(begin <= N){
            System.out.print(begin+" ");
            begin=begin+1;
            increase(N,begin);
        }
        return;
    }

【讨论】:

    【解决方案2】:

    您必须创建一个额外的private 方法来计算当前值。

    public static void increase(int N) {
        increase(1, N);
    }
    
    private static void increase(int a, int N) {
        if (a <= N) {
            if (a > 1)
                System.out.print(' ');
    
            System.out.print(i);
            increase(a + 1, N);
        }
    }
    

    【讨论】:

    • 由于拼写错误无法编译 - 方法调用应为 increase(1, N) 或私有方法的方法名称应为 private static void printNumbers(...)
    • @maloomeister 明白了!谢谢。
    【解决方案3】:

    你可以把a放在函数外面:

    // I don't know your class
    private a = 1;
    
    static void increase(int N){
            
        int a = 1;
        if(b <= N){
            System.out.print(a+" ");
            a=a+1;
        
            
        }
        else
        {
            increase(N);                
        }
    
    }
    

    【讨论】:

      【解决方案4】:
      static void increase(int N, int a){
          if (a>N) return;
          System.out.print(a+" ");
          a=a+1;
          increase(N,a);
      }
      
      //example call from static context print 1-100
      increase(100,1);
      

      【讨论】:

        猜你喜欢
        • 2018-08-18
        • 2021-12-09
        • 2015-02-09
        • 2015-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-05
        相关资源
        最近更新 更多