我一直在寻找这个问题,并且一直在使用纯粹的for循环来接收答案。我到目前为止的代码如下:
import java.util.Scanner;
public class HollowSquare {
public static void main(String args[]) {
Scanner ma = new Scanner(System.in);
System.out.print("Enter the number:");
int max = ma.nextInt();
for (int i = 1; i <= max; i++) {
for (int j = 1; j <= max; j++) {
if ((i == 1) || (i == max)) {
System.out.print("*");
} else {
if (j == 1 || j == max) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
}
System.out.println();
}
}
}
虽然我理解递归的概念,但我不确定如何在这个领域实现它,在这一点上,我一直在研究各种if语句和使用全局变量(可能不是最好的想法,但我对递归的概念比较新。)
我希望能够比现在更好地理解递归,这是我目前在递归方面无法理解的问题之一。
感谢任何能够提供帮助的人和所有人!
答案 0 :(得分:0)
仅用于递归。我甚至有一个递归方法,repeatMiddleLine
,调用一个本身递归的不同方法,repeatChar
。
public class HollowSquare {
private static final char squareChar = '*';
private static final char holeChar = ' ';
public static void main(String[] args) {
try (Scanner ma = new Scanner(System.in)) {
System.out.print("Enter the number:");
int max = ma.nextInt();
repeatChar(squareChar, max);
System.out.println();
repeatMiddleLine(max - 2, max);
repeatChar(squareChar, max);
System.out.println();
}
}
private static void repeatMiddleLine(int lineCount, int lineLength) {
if (lineCount > 0) {
System.out.print(squareChar);
repeatChar(holeChar, lineLength - 2);
System.out.println(squareChar);
repeatMiddleLine(lineCount- 1, lineLength);
}
}
private static void repeatChar(char c, int count) {
if (count > 0) {
System.out.print(c);
repeatChar(c, count - 1);
}
}
}
当我输入4时,它会打印:
****
* *
* *
****
和你一样,我没有做任何输入验证。用户可能键入-30,我不知道输出是什么,可能是几行空行。或20000000,可能是堆栈溢出。输入1打印2行,每行包含一个星号。在这种情况下,我相信你的循环表现更好。如果你愿意,你可以修理它。
答案 1 :(得分:0)
基本思路是编写递归方法,以便跟踪一半行数的行,并且:
步骤(3)稍微复杂,检查是否应该跳过,如果你已经过了一半并且n
有一个奇数值,在这种情况下你不想写额外的线。
这是用Ruby编写的。我不想给你答案,Ruby实际上是伪代码,除非你可以实际运行它。
def print_all_stars(n)
puts '*' * n # print n asterisks on a line
end
def print_end_stars(n)
puts '*' + (' ' * (n - 2)) + '*' # print an asterisk, n-2 spaces, and an asterisk
end
# The following method takes two arguments, but the 2nd arg
# has a default value if not explicitly specified. This negates
# the need for end users to kick-start things by calling
# print_square(n, n), which would probably confuse people.
def print_square(n, current_level = n)
# recursive base case, start backing out if we're halfway through the square
return if current_level <= n / 2
# step 1.
if current_level == n
print_all_stars(n)
else
print_end_stars(n)
end
# step 2.
print_square(n, current_level - 1) # recursive call!
# Work done after the recursive call happens in reverse order,
# as we back out of the call stack. The following will print
# the bottom half of the square, mirroring the top half except
# for the case where n is odd. In that case, we only want this
# level of the recursion to print one line, not two.
# step 3.
if current_level == n
print_all_stars(n)
elsif current_level > (n + 1) / 2 # here's the odd n check
print_end_stars(n)
end
end
print_square(3)
# produces:
#
# ***
# * *
# ***
print_square(4)
# produces:
#
# ****
# * *
# * *
# ****