Home > Mobile >  I'm struggling with the following pattern in java
I'm struggling with the following pattern in java

Time:10-17

The pattern I want to print is

1
1#
1#2
1#2#
1#2#3
1#2#3#

I wrote the following code:

public class Main {
    public static void main (String args[]) {
        int q = 2;
        for (int i = 1; i <= 6; i  ) {
            for (int j = 1; j <= i; j  ) {
                if (j % 2 != 0) {
                    if (j > 2) {
                        System.out.print (q  "");
                    } else {
                        System.out.print (j   "");
                    }
                } else {
                    System.out.print("# ");
                }
            } 
            System.out.println();
        }
    }
}

and it's output is:

1
1# 
1# 2
1# 2# 
1# 2# 2
1# 2# 2# 

CodePudding user response:

You can simply do it like this:

public class Main {
    public static void main(String args[]) {
      StringBuilder s = new StringBuilder();
      for (int i = 1; i <= 3; i  ) {
          s.append(i);
          System.out.println(s);
          s.append("#");
          System.out.println(s);
      }
    }
}

Just keep adding to the string(builder) and print it.

Or, if you don't want to track the state with the StringBuilder, you could do it like this:

public class Alternative {
    public static void main(String args[]) {
        int n = 3;
        for (int i = 0; i < n * 2; i  ) {
            for (int j = 0; j <= i; j  ) {
                if (j % 2 == 0) {
                    System.out.print(j / 2   1);
                } else {
                    System.out.print("#");  
                }
            }
            System.out.println();
        }
    }
}

CodePudding user response:

You are getting wrong output because of logic you have written. You can try below code snippet for the same pattern :

public class Main {
        public static void main(String args[]) {
            for (int i = 1; i <= 6; i  ) {
                int q = 1;
                for (int j = 1; j <= i; j  ) {
                    if (j % 2 == 0) {
                        System.out.print("#");
                    } else {
                        System.out.print(q);
                        q  ;
                    }
                }
                System.out.println();
            }
        }
    }
  • Related