如何使用两个for循环制作形状?我似乎无法使增量正确,我不确定它应该如何嵌套。我知道如何制作一个有星星的空心盒子但却无法弄清楚如何制作这些:
这是我尝试过的代码:
System.out.print("How big should the shape be? ");
Scanner scr = new Scanner(System.in);
int x = scr.nextInt();
drawShape(x);
public static void drawShape(int x) {
for(int i = 1; i <= x + 1; i++) {
System.out.println("//\\\\");
System.out.print("/");
for(int j = 1; j <= x * 2; j++) {
System.out.print("**");
}
System.out.print("\\");
System.out.println("//\\\\");
}
}
答案 0 :(得分:0)
如果我正确理解了问题,那么这是一个快速的代码段。
像这样更改drawShape()
方法:
public static void drawShape(int x) {
/* Start Printing Shapes */
for(int i = 2; i <= x; i++) {
/* Set Open */
char[] open = new char[i];
Arrays.fill(open,'/');
/* Set Close */
char[] close = new char[i];
Arrays.fill(close,'\\');
/* Set Stars */
char[] astx = new char[i*2 - 2];
Arrays.fill(astx,'*');
/* Print Header */
System.out.println(new String(open) + new String(close));
/* Print Stars */
System.out.println("/" + new String(astx) + "/");
/* Print Footer */
System.out.println(new String(close) + new String(open));
}
/* Line Break */
System.out.println();
}
以下是使用循环的另一种解决方案:
public static void drawShape(int x) {
/* Start Printing Shapes */
for(int i = 2; i <= x; i++) {
/* Set Open & Close */
char[] open = new char[i];
char[] close = new char[i];
for(int k = 0; k < i; k++) {
open[k] = '/';
close[k] = '\\';
}
/* Set Stars */
char[] astx = new char[i*2 - 2];
for(int k = 0; k < i*2 - 2; k++) {
astx[k] = '*';
}
/* Print Header */
System.out.println(new String(open) + new String(close));
/* Print Stars */
System.out.println("/" + new String(astx) + "/");
/* Print Footer */
System.out.println(new String(close) + new String(open));
}
/* Line Break */
System.out.println();
}
以下是该计划的输出:
//\\
/**/
\\//
///\\\
/****/
\\\///
////\\\\
/******/
\\\\////