//采用 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);
}
}