Java 如何使用两个for循环生成形状
如何使用两个for循环生成形状?我似乎不能得到正确的增量,我不确定它应该如何嵌套。我知道如何制作带有星星的空心盒子,但不知道如何制作: 这是我尝试过的代码:Java 如何使用两个for循环生成形状,java,for-loop,Java,For Loop,如何使用两个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) {
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("//\\\\");
}
}
System.out.print(“形状应该有多大?”);
扫描仪scr=新扫描仪(System.in);
int x=scr.nextInt();
拉伸形状(x);
公共静态空白绘图形状(int x){
对于(inti=1;i如果我正确理解了问题,那么这里有一个快速代码片段
更改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();
}
谢谢!我是编程新手,现在还不会使用数组……你知道一种简单的循环使用方法吗?谢谢!我是编程新手,现在还不会使用数组……你知道一种简单的循环使用方法吗?@Danes添加了另一种使用循环的解决方案。
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();
}
//\\
/**/
\\//
///\\\
/****/
\\\///
////\\\\
/******/
\\\\////