我需要编写一个方法来打印下面指定的星形图案。该方法的签名仅传入1个参数,无法更改。
该方法也不能有循环,必须简单地调用自身并递归地解决问题。您只能使用一种方法来解决此问题,而不能使用多种方法。
public static void main(String[] args) {
// Variables
Scanner in = new Scanner(System.in);
Boolean go = true;
int num;
String answer;
// Error catching structure
do {
try {
// Take input
System.out.print("Enter a number > 1: ");
num = in.nextInt();
// Check to make sure num>1
if (num <= 1) throw new Exception();
// Call the method
System.out.println(printAsterisk(num));
// Ask if the user wants to repeat
System.out.print("Enter 'y' to repeat or 'n' to stop: ");
answer = in.next().toLowerCase();
// Check to see if we repeat
if (answer.equals("n")) go = false;
else if (answer.equals("y")) go = true;
else {
System.out.println("Invalid input, program terminated.");
break; // stops the program
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input try again!");
in.next(); // discards old token
}
catch (Exception e) {
System.out.println("Number is less than or equal to 1! Try again!");
}
}while(go);
}
public static String printAsterisk(int n) {
// Base case
if (n == 0) return "";
// Recursive Call
String str = '*' + printAsterisk(n-1);
System.out.println(str);
return str;
}
调用printAsterisk(4)时,所需的输出应如下所示:
*
**
***
****
****
***
**
*
但是,当像这样调用printAsterisk(4)时,我的方法将输出以下内容:
*
**
***
****
****
https://stackoverflow.com/questions/52789416
复制相似问题