用星星打印男人的楼梯

  • 本文关键字:男人 星星 打印 java
  • 更新时间 :
  • 英文 :


我应该完成该方法

public static void printStairs(int numMen) {
}

哪些打印

o  ******
/| *    *
/  *    *
o  ******    *
/| *         *
/  *         *
o  ******         *
/| *              *          
/  *              *          
*********************

我得到了

public static void printStairs(int numMen) {
for (int i = 0; i < numMen; i++) {
String space = "";
String space2="";
for (int j = numMen - i; j > 1; j--) {
space += "     ";
}
for (int j = 2; j <=numMen-i; j++) {
space2 += "     ";
}
System.out.println(space + "  o  ******"+space2+"*");
System.out.println(space + " /|\ *    "+space2+"*");
System.out.println(space + " / \ *    "+space2+"*");

}
for(int i=0; i<=5*numMen+6; i++){
System.out.print("*");
}  
}

这给了

o  ******       *
/| *          *
/  *          *
o  ******   * 
/| *      *   
/  *      *
o  *******        
/| *    *          
/  *    *         
***********

而不是我想要的图像。

我不明白为什么这不起作用,因为我只是颠倒了楼梯左侧空间的代码并将其连接到楼梯右侧。

有人知道如何将垂直线合并到代码中并创建预期的图像吗?

试试这个:

public static void  printMan(int numMen) {
for (int i = 0; i < numMen; i++) {
String space ="" ,space2 ="";
for(int j = numMen-i; j>1; j--) { 
space += "       ";
}
for(int k = 0; k<i ; k++) { 
space2 += "       ";
}
System.out.println(space +" o  *****" + space2 + "*");
System.out.println(space + "/|\ *    "+ space2 + "*");
System.out.println(space + "/ \ *    "+ space2 + "*");             
}
for (int i = 0; i < (numMen *10)-((numMen-1) *3); i++) {
System.out.print("*");
}
}
}

从概念上讲,在几个位置的平方上循环应该更容易:

public static void printStairs(int numMen)
{
String[] manLines = {
" o  *****",
"/| *    ",
"/  *    "
};
final int rows = manLines.length;
for (int y = 0; y < numMen; ++y) {
for (int yrow = 0; yrow < rows; ++yrow) { // rows per man
for (int x = 0; x < y; ++x) {
System.out.print("    ");
}
System.out.print(manLines[yrow]);
for (int x = y; x < numMen; ++x) {
System.out.print("    ");
}
System.out.println("*");
}
}
}

使用字符数组可以简化操作。为了它的价值...

private static final char[][] figure = new char[][] { "  o  ******".toCharArray(), 
" /|\ *".toCharArray(), 
" / \ *".toCharArray()};
private static void printStairs(int numMen)
{
int stairs = numMen + 1;
int width = (stairs * 5) + 1;
for (int i = 0; i < numMen; i++)
{
for (char[] part : figure)
{
char[] line = newLine(width, ' ');
// start at least the 11 back from the end - back another 5 for each step
System.arraycopy(part, 0, line, width - 11 - i * 5, part.length);
System.out.println(line);
}
}
System.out.println(newLine(width, '*'));
}
private static char[] newLine(int width, char fill)
{
char[] line = new char[width];
Arrays.fill(line, fill);
line[width - 1] = '*';
return line;
}

最新更新