代码一样,就是如果你写一个可重用的helper方法重复代码编写要容易得多。
这就是所谓的干原理(Don't Repeat Yourself)。
在这种情况下,您希望为箭头打印'*'
的重复字符,并为缩进重复' '
(空格)的字符。因此,写一个方法用于创建重复字符的String
:
private static String repeat(char ch, int count) {
char[] buf = new char[count];
Arrays.fill(buf, ch);
return new String(buf);
}
现在你已经是,打印右箭头突然轻松了不少:
private static void printRightArrow(char ch, int n) {
for (int i = 1; i < n; i++)
System.out.println(repeat(' ', n - 1) + repeat(ch, i));
System.out.println(repeat(ch, n * 2 - 1));
for (int i = n - 1; i >= 1; i--)
System.out.println(repeat(' ', n - 1) + repeat(ch, i));
}
测试和输出
printRightArrow('*', 3);
printRightArrow('#', 7);
*
**
*****
**
*
#
##
###
####
#####
######
#############
######
#####
####
###
##
#
在另一个方向上印刷箭头非常相似:
private static void printLeftArrow(char ch, int n) {
for (int i = 1; i < n; i++)
System.out.println(repeat(' ', n - i) + repeat(ch, i));
System.out.println(repeat(ch, n * 2 - 1));
for (int i = n - 1; i >= 1; i--)
System.out.println(repeat(' ', n - i) + repeat(ch, i));
}
private static void printUpArrow(char ch, int n) {
for (int i = 1; i <= n; i++)
System.out.println(repeat(' ', n - i) + repeat(ch, i * 2 - 1));
for (int i = 1; i < n; i++)
System.out.println(repeat(' ', n - 1) + ch);
}
private static void printDownArrow(char ch, int n) {
for (int i = 1; i < n; i++)
System.out.println(repeat(' ', n - 1) + ch);
for (int i = n; i >= 1; i--)
System.out.println(repeat(' ', n - i) + repeat(ch, i * 2 - 1));
}
测试和输出
printRightArrow('*', 5);
printLeftArrow('*', 5);
printUpArrow('*', 5);
printDownArrow('*', 5);
*
**
***
****
*********
****
***
**
*
*
**
***
****
*********
****
***
**
*
*
***
*****
*******
*********
*
*
*
*
*
*
*
*
*********
*******
*****
***
*
在r = 3以外的行上,使用适当数量的空格开始行。在r = 3行,用许多星号开始。试着将问题分解为基本要素,希望你会发现每一个要素都是可行的。 – yshavit
我说,不要为你的第一个for循环输出println,而只是输出。然后在打印后加一个if-else,如果'x = n1'则输出'n1 - 1'更多的星号,然后移动到新的一行,否则就移动到一个新的行。 – skwear
对不起,忘了空格。我稍后会发布解决方案,但这个想法是一样的。这可能实际上是Code Golf SE的东西:) – skwear