0

// int を受け取り、その数の星を出力する再帰メソッド。//最初の if ステートメントが適切な Java 形式ではないことはわかっていますが、階乗 = (n-1) と同じ行に nStars(n) があると、コンパイル中にエラーが発生します。

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 に答える