简体   繁体   中英

Number Pattern in Java

I am trying to make a program that outputs
这种模式。

So far I have done:

public class printPattern {
  public static void main(String[] args) {
  int a = 6;
  int i, j;
  int max = 1;
  int num;

  for(i = 1; i <= a; i++){
  num = 1;
  System.out.println("0");
    for(j = 1; j <= max; j++){
    System.out.print(num);
    System.out.print(" ");
    num++;
    }
  max++;
  }
  }
}

But the output I am getting is

这个。

The "0" is there to show the spaces, but I want to remove the entire line which contains the first "0" so that the output starts with a "1". I am unsure what to change. Any help would be much appreciated. Thank You.

I suggest adding conditions (if we need to print out delimiters ):

   for (int i = 1; i <= a; ++i) {
     if (i > 1)
       System.out.println();   // more than 1 line, need delimiter (new line)

     for (int j = 1; j <= i; ++j) {
       if (j > 1) 
         System.out.print(" "); // more than 1 column, need delimiter (space)

       System.out.print(j);
     }   
   }

Most shortest form:

String str = "";
for (int i = 1; i <= 6; i++) {
  str = str + " " + i;
  System.out.println(str);
}

Output:

 1
 1 2
 1 2 3
 1 2 3 4
 1 2 3 4 5
 1 2 3 4 5 6

Here what I've got

Here you can check https://code.sololearn.com/c9ALHSGAa6ZZ

class printPattern {
    public static void main(String[ ] args) {
          int a = 6;
          int i, j;
          int max = 1;
          int num;

          for (i = 1; i <= a; i++) {
            num = 1;
            for (j = 1; j <= max; j++) {
                System.out.print(num);
                System.out.print(" ");
                num++;
            }
            System.out.println();
          max++;
          }
    }
}
    public class printPattern {
      public static void main(String[] args) {
      int a = 6;
      int i, j;
      int max = 1;
      int num;

      for(i = 1; i <= a; i++){
      num = 1;

        for(j = 1; j <= max; j++){
        System.out.print(num);
        System.out.print(" ");
        num++;
        }
       System.out.println(" ");
      max++;
      }
      }
    }

this is working as you asked. just remove 0 from print statement

How about this ?

public void pyramid(int size) {

    for(int i = 1; i <= size; i++) {
        for(int j = 1; j <= i; j++) {
            System.out.print(j + " ");
        }
        System.out.println("");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM