您的位置:首页 > 编程语言 > Java开发

for循环输出“*”打印房屋形状

2017-11-23 21:53 309 查看
/*
用for循环输出"*"打印房屋形状

      

     ******      

    *****  *     

   *****    *    

  *****      *   

 *****        *  

*****          * 

****************

*              *

*              *

*              *

*              *

****************

*/

public class ForHouse {

public static void main(String[] args) {
// 房顶的行数,行数n可变,房屋大小可随n成比例增大或缩小

int n = 5;
drawHouse(n);
}

public static void drawHouse(int n) {
// up:house上半部
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= 2 * n; j++) {
if (j == n - i + 1) {
System.out.print("*****");
} else if (j == n + i - 1) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
// 房屋下半部,矩形
// 墙壁 (int) Math.ceil(n * 3 / 5); 向上取整,成比例增高墙壁的高度
int m = (int) Math.ceil(n * 3 / 5);
// m:墙壁高度
for (int i = 1; i <= m + 2; i++) {
//矩形m + 2,,为房屋下半部矩形的总高度
for (int j = 1; j <= n * 2 + 3; j++) {
if (i == 1 || i == m + 2) {
// 矩形上部,下部
System.out.print("*");
} else if (j == 1 || j == n * 2 + 3) {
// 墙壁
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java for for循环 房屋