我必须制作一个程序,要求用户输入一个高度和一个长度(两个偶数),然后程序将绘制一个房子。房子的屋顶是(宽度/ 2)行数。示例程序应如下所示:
Enter height and width of the house you want me to draw (must be even numbers): 10 10
....**
.../..\
../....\
./......\
/........\
----------
|........|
|........|
|........|
|........|
|........|
|........|
|........|
|........|
|........|
|........|
----------
但这是我一直只为屋顶而设的,使用10和10的宽度和高度(我尚未启动身体):
height: 10
width: 10
....**
.../..\
.../..\
.../..\
.../..\
----------
是否有人知道如何放置正确的空间以使其看起来像样本?我的代码是:
import java.util.Scanner;
public class QuestionCode {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int height = 0, width = 0;
String space = ".", left = "/", right = "\\";
System.out.print("height: ");
height = keyboard.nextInt();
System.out.print("width: ");
width = keyboard.nextInt();
System.out.println();
int outerSpace = ((width/2)-1);
int halfWidth = ((width/2)-2);
while (outerSpace > 0) {
System.out.print(space);
--outerSpace;
}
System.out.println("**");
while (halfWidth >= 0) {
outerSpace = ((width/2)-2);
while (outerSpace > 0) {
System.out.print(space);
--outerSpace;
}
System.out.print(left);
int innerSpace = 2;
while (innerSpace < (width-2)) {
System.out.print(space);
innerSpace *= 2;
}
System.out.println(right);
halfWidth--;
}
while (width > 0) {
System.out.print("-");
--width;
}
}
}
答案 0 :(得分:2)
在您的下方,我会找到使用for
循环进行此操作的提议。
这种练习效率要高得多,因为你事先知道你要循环多少次。
基本上,我使用了width
和height
以外的其他两个变量:
heightRoof
:知道我想为我的屋顶排多少行。
middle
:要知道在停止前我必须在第一行画多少分。
从那里开始,使用嵌套循环是可行的方法,因为我们确切地知道我们想要拥有多少点和行,其余的是逻辑思维。
int width = 10;
int height = 10;
int middle = width % 2 == 0 ? (width / 2) - 1 : width / 2;
int heightRoof = middle+1;
for (int i = 0 ; i < heightRoof ; i++){
for (int j = middle - i - 1 ; j >= 0 ; j--){
System.out.print(".");
}
if (i == 0) {
System.out.print("**");
System.out.println();
continue;
} else {
System.out.print("/");
for (int k = 0 ; k < 2*i ; k++){
System.out.print(".");
}
}
System.out.print("\\");
System.out.println();
}
for (int i = 0 ; i < width ; i++){
System.out.print("-");
}