我正在尝试使用嵌套的for循环显示一个星号菱形。
到目前为止,这是我的代码:
public class Diamond { public static void main(String[] args) { int size = 9; for (int i = 1; i <= size; i += 2) { for (int k = size; k >= i; k -= 2) { System.out.print(" "); } for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); }// end loop for (int i = 1; i <= size; i += 2) { for (int k = 1; k <= i; k += 2) { System.out.print(" "); } for (int j = size; j >= i; j--) { System.out.print("*"); } System.out.println(); }// end loop } }
这很接近,但是我要两次打印9个星号。
如何调整第二个for循环以7个星号和2个空格开始输出?
谢谢您的帮助!
在您的第一个for循环中,删除=标记,然后使用<例如 for (int i = 1; i < size; i += 2)
for (int i = 1; i < size; i += 2)
完整代码
int size = 9; for (int i = 1; i < size; i += 2) { for (int k = size; k >= i; k -= 2) { System.out.print(" "); } for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); }// end loop for (int i = 1; i <= size; i += 2) { for (int k = 1; k <= i; k += 2) { System.out.print(" "); } for (int j = size; j >= i; j--) { System.out.print("*"); } System.out.println(); }// end loop