如何简化这些For-Loops?

时间:2014-12-21 06:44:39

标签: java loops for-loop while-loop simplify

以下内容的输出为display this

enter image description here

我的问题是,由于我使用了多个For-Loops,我可以更简化它们吗?
比如,我可以在单个For循环中添加多个初始化语句吗?

public class diamond    {
    public static void main(String[] args) {
        for (int c=1; c<=10; c++) {
            for (int d=1; d<=11-c; d++) {
                System.out.print("*");
            }
            for (int e=2; e<c*2; e++) {
                System.out.print(" ");
            }
            for (int i=1; i<=11-c; i++) {
                System.out.print("*");
            }
            System.out.println();
        }
        for (int f=2; f<=10; f++) {
            for (int g=1; g<=f; g++) {
                System.out.print("*");
            }
            for (int h=2; h<22-f*2; h++) {
                System.out.print(" ");
            }
            for (int j=1; j<=f; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

6 个答案:

答案 0 :(得分:3)

关键是要注意代码中的重复模式并将其考虑在内。

您可以使用辅助方法打印一系列N个字符:

public static void printNTimes(char value, int n) {
    for (int i = 0; i < n; i++) {
        System.out.print(value);
    }
}

您可以通过对所涉及的字符和钻石的大小使用常量来概括该方法。

private static final char OuterChar = '*';
private static final char InnerChar = ' ';
private static final int Size = 10;

并添加另一个辅助方法来打印一行,其中外部有一个字符的N个实例,内部有2 * (Size - N)个字符:

private static void printRow(int n) {
    printNTimes(OuterChar, n);
    printNTimes(InnerChar, (Size - n) * 2);
    printNTimes(OuterChar, n);
    System.out.println();
}

然后您的代码变为:

public class diamond
{
    private static final char OuterChar = '*';
    private static final char InnerChar = ' ';
    private static final int Size = 10;

    public static void printNTimes(char value, int n) {
        for (int i = 0; i < n; i++) {
            System.out.print(value);
        }
    }

    private static void printRow(int n) {
        printNTimes(OuterChar, n);
        printNTimes(InnerChar, (Size - n) * 2);
        printNTimes(OuterChar, n);
        System.out.println();
    }

    public static void main(String[] args) {
        for (int c = Size; c >= 1; c--) {
            printRow(c);
        }
        for (int c = 2; c <= Size; c++) {
            printRow(c);
        }
    }
}

答案 1 :(得分:1)

int max=9,min=10;
        for(int i=0;i<19;i++){
            for(int j=0;j<20;j++){

                if(j<min || j>max){
                    System.out.print("*");
                }
                else{
                    System.out.print(" ");
                }
            }
            if(i<9){
                min--;
                max++;
            }
            else {
                min++;
                max--;
            }
            System.out.println();
        }

答案 2 :(得分:1)

我觉得这个很清楚,但YMMV。

for( int i = 10; i >= 1; i-- ){
    String s = "**********".substring(0, i);
    System.out.printf( "%-10s%10s\n", s, s );
}
for( int i = 1; i <= 10; i++ ){
    String s = "**********".substring(0, i);
    System.out.printf( "%-10s%10s\n", s, s );
}

答案 3 :(得分:0)

因为这在循环中重复:

  for (int d=1; d<=11-c; d++)
     {
        System.out.print("*");
     }

您可以将其写入变量并将其打印两次。这将消除两个循环。 (每个外环中有一个子循环)

答案 4 :(得分:0)

我喜欢在易于阅读和维护的代码中包装逻辑,因此我没有使用嵌套的for循环来编写带有描述性方法的类。

package se.wederbrand.stackoverflow.diamond;

import java.util.ArrayList;
import java.util.List;

public class Diamond {
    final List<String> rows;


    public static void main(String[] args) {
        System.out.println(new Diamond(10));
    }

    public Diamond(int width) {
        this.rows = new ArrayList<>();
        for (int stars = 1; stars <= width; stars++) {
            // add all rows, start from the middle and build around it
            addRows(stars, width);
        }
    }

    private void addRows(int stars, int width) {
        String row = generateRow(stars, width);
        // add on top
        this.rows.add(0, row);
        if (stars > 1) {
            // add to bottom
            this.rows.add(row);
        }
    }

    private String generateRow(int stars, int width) {
        String row = "";
        int spaces = width - stars;
        for (int j = 0; j < stars; j++) {
            row += "*";
        }
        for (int j = 0; j < spaces; j++) {
            row += "  ";
        }
        for (int j = 0; j < stars; j++) {
            row += "*";
        }
        return row;
    }

    @Override
    public String toString() {
        String diamond = "";
        for (String row : rows) {
            diamond += row + System.lineSeparator();
        }
        return diamond;
    }
}

答案 5 :(得分:0)

这是一个有趣的问题,你可以看到每个人如何采用不同的方法来解决它。这种方式只会给你一个字符串,用另一边的另一个字符“填充”。

public static void main(String[] args) {
    for (int c = 1; c <= 10; c++) {
        System.out.println(printPadded(11 - c, '*',  (c - 1) * 2, ' '));
    }
    for (int f = 10; f >= 2; f--) {
        System.out.println(printPadded(11 - f, '*',  (f - 1) * 2, ' '));
    }
}

public static String printPadded(int padCount, char padCharacter, 
          int middleCount, char middleCharacter) {
    StringBuilder s = new StringBuilder(padCount * 2 + middleCount);
    for (int i = 0; i < padCount; i++) {
        s.append(padCharacter);
    }
    for (int i = 0; i < middleCount; i++) {
        s.append(middleCharacter);
    }
    for (int i = 0; i < padCount; i++) {
        s.append(padCharacter);
    }
    return s.toString();
}