2

For my java class one of the exercises is to print out a diamond using nested for loops. In the exercise you need to use the minimum amount of outputs, while using nested for loops. The other stipulation is that each output can only output 1 character such as a single space, a single asterisk, or a single end line statement.

I've finished it but i was wondering if there was an easier way to do it, or if anyone has tips on cleaning up my code. It just seems like ended up writing way more than was needed. Any help and tips are greatly appreciated. :)

Here is what the end result needs to look like:

Here is my code:

public class Diamond 
{
    public static void main(String args[])
    {
        int b = 11; // secondary asterisk loop counter
        int ac = 2; // asterisk count
        int sc = 5; // space count
        int elc = 2; // end line count
        int slc = 1; // space loop count
        int sslc = 1; // secondary space loop count


        for(int e = 1; e < elc && elc < 12;e++)
        {   
            if(elc <= 6)
            {
                for(int a = 1; a < ac; a++)
                {
                        for(;sc <= 5 && sc > 0; sc--)
                        {
                            System.out.print(" ");
                        }

                        System.out.print("*");
                }

                ac += 2;
                sc = 5 - slc;
                slc += 1;
            }

            else if (elc > 6)
            {
                ac -= 2;
                sc = 1;


                for (; b < ac ; b++)
                {

                    for(;sc <= sslc && sc > -2; sc++) 
                    {
                        System.out.print(" ");
                    }

                    System.out.print("*");
                }

                b = 1;
                sslc += 1;

            }
            if(elc != 6)
            {
                System.out.println();
            }

            elc += 1;
        }
    }
}
4

2 回答 2

0
public class ASultan
{
   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();
    }

    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();
    }

  }
}
于 2014-11-30T07:34:07.287 回答
0

您可以尝试将钻石的 4 个边缘写成方程式(例如 x+y=4;xy=2...)。然后只需对网格中的每个单元格进行嵌套循环,看看是否应该打印空格或星号。测试看起来像

如果 f1(x,y) 或 f2(x,y) 或 f3(x,y) 或 f4(x,y):打印 '*' 否则打印 ' '

其中 f1,f2,f3,f4 是 4 条对角线的方程。

如果需要尽量减少要打印的字符数,要么使用数组进行准备,然后忽略尾随空格;或使用一些临时规则(比如每行只有 2 颗星,除了第一个和最后一个......)

于 2012-09-22T02:12:50.480 回答