2

How do I print this?

!!!!!!!!!!!!!!!!!!!!!!
\\!!!!!!!!!!!!!!!!!!//
\\\\!!!!!!!!!!!!!!////
\\\\\\!!!!!!!!!!//////
\\\\\\\\!!!!!!////////
\\\\\\\\\\!!//////////

I have:

public class SlashFigure {
    public static void main(String[] args){
        first();
    }
    
    

        public static void first() {
            for ( int i= 1; i<=6; i++) {
                for (int l = 0; l <= 2 * i -2; l++) {
                    System.out.print("\\");
                }
                        for (int e = 22; e >= -2*i + 26; e-=1) {
                            System.out.print("!");
                        }
                                for (int r = 0; r <= 2 * i -2; r++) {
                                    System.out.print("/");
                                }
                      System.out.println();
            }
        }
    }

and it's printing this:

\/
\\\!///
\\\\\!!!/////
\\\\\\\!!!!!///////
\\\\\\\\\!!!!!!!/////////
\\\\\\\\\\\!!!!!!!!!///////////
AstroCB
  • 12,337
  • 20
  • 57
  • 73
Marina Claire
  • 103
  • 1
  • 1
  • 11
  • See http://stackoverflow.com/questions/580269/reverse-iteration-through-arraylist-gives-indexoutofboundsexception/1063588#1063588 – Sualeh Fatehi Sep 28 '14 at 03:55

2 Answers2

1

you've written way more code than you need. The pattern for lines that you're showing is simply line * 2 * \ + 22 - line * 4 * ! + line * 2 * /, over exactly 6 lines, but it's always groups of 2 characters so we can divide all of that by 2, and observe that the \\ and // follow the same rule:

for(int i=0, j=0, k=0; i<6; i++) {
  for(j=0; j<i; j++) { System.out.print("\\\\"); }
  for(k=0; k<(11-2*i); k++) { System.out.print("!!"); }
  for(j=0; j<i; j++) { System.out.print("//"); }
  System.out.println();
}

Done.

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
0

You have multiple nested for loops, but you only need one overhead loop to approach line by line.

for(int i = 0; i < 6; i++){
    for(int k = 0; k < i*2; k++) System.out.print("\\");
    for(int j = i*2; j < 22 - (i*2); j++) System.out.print("!");
    for(int l = 0; l < i*2; l++) System.out.print("/");
    System.out.println();
}
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
mn4
  • 11
  • 1
  • and more efficienly with the initial `for(int i=0` being `for(int i=0,j=0,k=0)` and then using `for(k=0)` twice, for both '\\' and '//' since they're the same groups. – Mike 'Pomax' Kamermans Sep 28 '14 at 04:33