反转嵌套循环

时间:2012-11-20 01:28:31

标签: java for-loop reverse shape nested-loops

我正在尝试反转此代码,以便我可以打印带有边框的菱形。开始反转嵌套循环/一系列循环的最佳方法是什么?我尝试了修补代码,但一切都混乱而且乱序。有什么建议吗?

另外,有没有办法在顶部的星星两侧制作偶数个。?我能够使其工作的唯一方法是在每一方打印一个偶数......

以下是应该打印到控制台的内容:http://i.imgur.com/h55r2.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?
    }
}

2 个答案:

答案 0 :(得分:2)

这不是最优雅的方式,但它有效。将这些行插入代码中的“但是如何反转?”我已用注释

标记了对代码的更改
        // 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("-");

答案 1 :(得分:0)

如果你写了这样的建造者......

public static interface Reflection {
    String reflect(String str);
}

public static class Builder {
    private List<String> lines = new ArrayList<String>();
    private StringBuilder builder = new StringBuilder();
    public void newLine() {
        lines.add(builder.toString());
        builder = new StringBuilder();
    }
    public void repeat(String section, int count) {
        for (int i = 0; i < count; i++) {
            builder.append(section);
        }
    }
    public void padLeft(String section, int count) {
        while (builder.length() < count) {
            builder.append(section, 0, section.length());
        }
    }
    public void reflectX(Reflection reflection) {
        List<String> reflected = new ArrayList<String>();
        for (String line : lines) {
            StringBuilder tmp = new StringBuilder();
            tmp.append(reflection.reflect(line));
            tmp.reverse();
            tmp.append(line);
            reflected.add(tmp.toString());
        }
        lines = reflected;
    }
    public void reflectY(Reflection reflect) {
        List<String> reflection = new ArrayList<String>();
        for (String line : lines) {
            reflection.add(reflect.reflect(line));
        }
        Collections.reverse(reflection);
        lines.addAll(reflection);
    }
    public String build() {
        StringBuilder tmp = new StringBuilder();
        for (String line : lines) {
            tmp.append(line);
            tmp.append('\n');
        }
        return tmp.toString();
    }
    public void write(String string) {
        builder.append(string);
    }
}

然后将您的代码简化为此,但这只是过度工程:

int nRows = 8;
int pad = 20;
Builder builder = new Builder();

builder.write("_");
builder.padLeft(" ", pad);
builder.newLine();

for (int i = 0; i < nRows; i++) {
    int dots = i * 2 + 1;
    int stars = i >= 4 ? 4 : 0;
    builder.repeat("*", stars);
    builder.repeat(".", dots - stars);
    builder.write("\\");
    if (i < nRows - 1) {
        builder.write("_");
    }
    builder.padLeft(" ", pad);
    builder.newLine();
}
builder.reflectX(new Reflection() {
    @Override
    public String reflect(String str) {
        return str.replace('\\', '/');
    }
});
builder.reflectY(new Reflection() {
    @Override
    public String reflect(String str) {
        return str.replace("\\", "%x").replace("/", "\\").replace("%x", "/").
                replace("_\\", "%x").replace("/_", "_/").replace("%x", "\\_");
    }
});
System.out.println(builder.build());

结果

               __                   
             _/..\_                 
           _/......\_               
         _/..........\_             
       _/..............\_           
     _/.....********.....\_         
   _/.......********.......\_       
 _/.........********.........\_     
/...........********...........\    
\...........********.........../    
 \_.........********........._/     
   \_.......********......._/       
     \_.....********....._/         
       \_.............._/           
         \_.........._/             
           \_......_/               
             \_.._/                 
               __