java Java递归从一个方法调用中打印星号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16158829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Recursion printing asterisks from one method call
提问by Joe Paty
I have an assignment introducing Recursion in Java and I am running into a roadblock. The assignment requires a recursion method to output a number of lines of a number of asterisks depending on the integer value passed to it. For example, if 4 is passed in as variable n, the output would have a first line of one asterisk, next line 2 asterisks, next 3 asterisks, next 4, then 4, 3, 2, & 1 going down.
我有一项介绍 Java 中递归的作业,但遇到了障碍。该赋值需要一种递归方法,根据传递给它的整数值输出若干行的若干星号。例如,如果 4 作为变量 n 传入,则输出将有一个星号的第一行,下一行 2 个星号,接下来的 3 个星号,接下来的 4,然后是 4、3、2 和 1。
I have been able to complete the first half of the output (not sure if it is optimal though), but have no clue how to get the method to reverse back down. This is all to be done in one method call with a variable (n) passed to the method.
我已经能够完成输出的前半部分(虽然不确定它是否是最佳的),但不知道如何让方法倒退。这一切都将在一个方法调用中完成,并将变量 (n) 传递给该方法。
Here is the method I have so far:
这是我到目前为止的方法:
public static void myMethod(int n)
{
if (n <= 1) {
System.out.print("*");
} else {
myMethod(n - 1);
for (int i = 0; i < n; i++) {
System.out.print("*");
}
}
System.out.print("\n"); // new line
}
It is called from main with this:
它是从 main 调用的:
myMethod(n);
So what I have is a for loop that will print an asterisk on the same line 'n' times. After the for loop it proceeds to the next line and cycles, changing n. But I have no idea how to get it to reverse.
所以我有一个 for 循环,它将在同一行“n”次打印一个星号。在 for 循环之后,它继续下一行并循环,改变 n。但我不知道如何让它逆转。
My method prints from the method. My instructor showed me a sample version passing 2 variables (n) and a null string.
我的方法从方法打印出来。我的导师向我展示了一个传递 2 个变量 (n) 和一个空字符串的示例版本。
public static String myMethod(int n, String displayStr) {
String currentStr = "";
for (int i = 0; i < n; i++)
currentStr += "*";
currentStr += "\n";
if (displayStr == null){
return myMethod((n - 1), currentStr);
} // end base case
else if (n > 0){
return myMethod((n - 1), (currentStr + displayStr + currentStr));
}
else {
return displayStr;
}
} // end recursion method myMethod
His version prints from main using the following code line:
他的版本使用以下代码行从 main 打印:
System.out.println(myMethod(n, null));
I have tried his version and it prints the triangle on it's side but the largest line only prints once instead of twice. I have spent all day trying to alter his to add in a duplicate line in the middle and am starting to think it isn't possible.
我试过他的版本,它在它的侧面打印三角形,但最大的线只打印一次而不是两次。我花了一整天的时间试图改变他在中间添加重复的行,我开始认为这是不可能的。
Any help would be GREATLY appreciated. I am at a complete standstill with this.
任何帮助将不胜感激。我对此完全停滞不前。
回答by Zim-Zam O'Pootertoot
Change the method signature to public static void myMethod(int n, boolean reversed)
where reversed
is initialized to false but flips to true when you print n
asterisks. Inside the method, reverse your logic if reversed
is true.
将方法签名更改为public static void myMethod(int n, boolean reversed)
wherereversed
初始化为 false 但在打印n
星号时翻转为 true 。在方法内部,如果reversed
为真,则反转您的逻辑。
回答by Supericy
You basically just need to print out the current row, then do the recursive call, then print the row again. That way, you get the stack buildup on the way up, and then again on the way down.
您基本上只需要打印出当前行,然后进行递归调用,然后再次打印该行。这样,你会在向上的过程中积累堆栈,然后在向下的过程中再次积累。
Here is an example that uses 2 parameters, one being the max length and the other being the iterator for the recursion.
这是一个使用 2 个参数的示例,一个是最大长度,另一个是递归的迭代器。
// bootstrap method to start the recursion
public static void myMethod(int length)
{
myMethod(length, length);
}
public static void myMethod(int length, int i)
{
if (i > 0)
{
int rowLength = length - i + 1;
printRow(rowLength, '*');
myMethod(length, i - 1);
printRow(rowLength, '*');
}
}
public static void printRow(int length, char symbol)
{
for (int i = 0; i < length; i++)
System.out.print(symbol);
System.out.println();
}
回答by Bohemian
Because the output counts up(not *down to zero), you must pass in the number of asterisks to print andthe maximum number, so the terminating condition can be established.
因为输出是向上计数(而不是*向下计数为零),所以必须传入要打印的星号数量和最大数量,这样才能建立终止条件。
Further, the pseudo code for your method is:
此外,您的方法的伪代码是:
- if n > max return (terminating condition)
- print n asterisks
- recursively call with n + 1
- print n asterisks
- 如果 n > 最大回报(终止条件)
- 打印 n 个星号
- 用 n + 1 递归调用
- 打印 n 个星号
A great deal of code simplification can be achieved if you pass in not the current length to print, but the String of asterisks, so your (private) recursive method could be simply:
如果您传入的不是要打印的当前长度,而是星号字符串,则可以实现大量代码简化,因此您的(私有)递归方法可能很简单:
private static void myMethod(int n, String s) {
if (s.length() < n) return;
System.out.println(s);
myMethod(n, s + "*");
System.out.println(s);
}
And your public method, which sets up the initial conditions, is then:
然后您设置初始条件的公共方法是:
public static void myMethod(int n) {
myMethod(n, "*");
}
IMHO an elegant implementation with good code density.
恕我直言,一个优雅的实现,具有良好的代码密度。