0

//采用 int 的递归方法,打印该数量的星星。//我知道第一个 if 语句不是正确的 java 格式,但是将 nStars(n) 与 factorial = (n-1) 放在同一行会在编译时给我一个错误。

public class RecursiveMethods {
    int theVal; 
    int factorial;


    public void nStars(int n) {

        if (n > 0) {
            factorial = (n-1);
            nStars(n);
            System.out.print("*");
      }
        else {
            System.out.print( "*");
      }
   }

  // recursively finds the binary of the int and prints the amount of 1s in the binary
    public int numOnes(int x) {

        int theVal = 0;

            if (x == 0) {
                theVal = theVal;
  }

            if (x % 2 == 1) {
                theVal = 1 + theVal;
                x = (x / 2);
                numOnes(x);
  }

            else if (x % 2 == 0) {
                theVal = 0 + theVal;
                x = (x / 2);
                numOnes(x);
  }


            return theVal;
  }

}

// here is the driver (Only done for the * method haven't gotten to numOnes driver)

import java.util.*;

public class RecursiveDriver { 
    private static Object userInput;
    public static void main(String[] args) {
       RecursiveDriver rd = new  RecursiveDriver();
       RecursiveMethods rm = new RecursiveMethods();


       System.out.println("How many stars do you want to see?");
       Scanner sc = new Scanner(System.in);
       int n = sc.nextInt();
       rm.nStars(n);

  }

}
4

1 回答 1

1

看看这段代码:

public void nStars(int n) {
    if (n > 0) {
        factorial = (n-1);
        nStars(n);  // <---- Look here
        System.out.print("*");
    }
    else {
        System.out.print( "*");
    }
}

请注意,此函数使用相同的参数调用自身。所以:

  • 当你打电话时nStars(n),它会打电话nStars(n)
  • 当调用nStars(n)发生时,它调用nStars(n).
  • 当调用nStars(n)发生时,它调用nStars(n).
  • 当调用nStars(n)发生时,它调用nStars(n).
  • 当调用nStars(n)发生时,它调用nStars(n).
  • 当调用nStars(n)发生时,它调用nStars(n).
  • ...

最终,您会因为同时激活太多递归调用而导致堆栈溢出。

你可能打算写这样的东西:

public void nStars(int n) {
    if (n > 0) {
        factorial = (n-1);
        nStars(n - 1);  // <---- Look here
        System.out.print("*");
    }
    else {
        System.out.print( "*");
    }
}

现在,您nStars使用参数进行调用n - 1,因此最终您将了解基本情况。不过,这里还有另一个错误。(我会把它留给你作为练习;它不会导致崩溃)

希望这可以帮助!

于 2014-10-01T19:59:33.873 回答