我正在尝试反转此代码,以便我可以打印一个带有边框的菱形形状。开始反转嵌套循环/一系列循环的最佳方法是什么?我尝试修改代码,但一切都变得困惑且无序。有什么建议吗?
另外,有没有办法在顶部星星的每一侧制作偶数个 . ?我能够使其工作的唯一方法是在每一面打印均匀的数量......
以下是应打印到控制台的内容:/image/SyYzp.jpg
这是我的代码:
public class SixTester {
public static void main(String[] args)
{
int i,j,k;
int numOfRows = 8; // Made this a variable, so that the program can make any size diamond (try playing around with different values eg. 2 or 16)
// Step 1. The first Dash
for(i=0;i<numOfRows*2 +2;i++)
System.out.print(" "); // Number of spaces is double the number of rows in your 'Half Pyramid'
System.out.println("-");
// Step 2. The First half diamond
for (j=0; j<numOfRows ; j++ )
{
for(k=numOfRows*2; k>1+j*2; k--)
System.out.print(" ");
System.out.print("_/");
for (i=0; i< 2+j*4; i++)
{
// Prepare the Star rectangle, Note that it starts half the way (rows/2)
if(j >= numOfRows/2 && (i>j*2- numOfRows/2 && i<j*2+ numOfRows/2)) {
System.out.print("*");
}
else
System.out.print(".");
}
System.out.println("\\_");
}
// Next Step - Make the bottom pyramid...but how to reverse?
}
}
最佳答案
这不是最优雅的方式,但它确实有效。在代码显示“但是如何反转?”的位置插入这些行我已用注释标记了对代码的更改
// COUNT BACKWARDS NOW. YOU WANT LARGEST ROW FIRST, OTHERWISE IT'S OK EXCEPT...
for (j=numOfRows-1; j>=0 ; j-- )
{
for(k=numOfRows*2; k>1+j*2; k--)
System.out.print(" ");
System.out.print("\\_"); // BORDERS ARE BACKWARDS. PUT BORDER ON OTHER SIDE
for (i=0; i< 2+j*4; i++)
{
if(j >= numOfRows/2 && (i>j*2- numOfRows/2 && i<j*2+ numOfRows/2)) {
System.out.print("*");
}
else
System.out.print(".");
}
System.out.println("_/"); // PUT BORDER ON OTHER SIDE
}
for(i=0;i<numOfRows*2 +2;i++)
System.out.print(" ");
System.out.println("-");
关于java - 反转嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13465286/