lundi 5 décembre 2016

I need to build a triangle with words using nested loops

I received an assignment from school. To build a Triangle with words using nested loops, like this http://ift.tt/2fZDfNr

I looked up some solutions on the internet, and found this code. Can anyone explain this code to me. It works, thats not the problem. I just can't understand the code, like the if statement after the for loops, what does it do? And it would be appreciated if someone gives another code for this assignment with using only nested loops (no string builder and cell padding). Thank You.

    public void printTriangle(String input) {  
    String tmp = input.substring(1);
    StringBuilder builder = new StringBuilder(tmp);
    builder = builder.reverse().append(input);
    String line = builder.toString();
    for(int i = 0; i < input.length(); i++){
        for(int j = 0; j < line.length(); j++){

            if(i + 1 == input.length() || Math.abs(j - line.length()/2) == i){
                System.out.print(line.charAt(j));
            }else{
                System.out.print(" ");
            }
        }
        System.out.println();
    }
}}

Aucun commentaire:

Enregistrer un commentaire