开发者

Creating number patterns in java

I need to create these patterns in java according to however many lines the user enters:

1
12
123
1234
12345

54321
4321
321
21
1


     1
    21
   321
  4321
 54321

I can do the first two but I cannot do the third.

Here is the code for the second:

public static void displayPatternII (int lines) {

    for (int i = 1; i <= lines; i++){
        for (开发者_如何学Cint j = lines + 1 - i; j > 0; j--)
            System.out.print (j + " ");
        System.out.println();
    }
}


 public static void displayPatternIII (int lines) {

    for (int i = 1; i <= lines; i++){
      System.out.print(" ");
        for (int j = lines; j > 0; j--)
            System.out.print (j > i ? " " : j);
        System.out.println();
    }
}


I would look at Formatter Instead of manually trying to pad the spaces. I also agree that your message is a bit confusing...


I will not give you an answer, but I will tell you what has to be done.

Lets take

1
12
123
1234
12345

From 1 to a particular number (from the user or whatever) (lets call this max) you print all the numbers from 1 to the current index

54321
4321
321
21
1

Same as the one above, but you loop backwards

     1
    21
   321
  4321
 54321

From 1 to max print n+1 spaces where n is the difference between the max and the current index


Since it looks like homework, I will give you a solution I doubt you can submit to give you some ideas. ;)

public static void main(String... args) {
    displayPatternIII(5);
}

public static void displayPatternIII(int lines) {
    int cols = lines + 2;
    for (int i = 0; i < cols * lines; i++) {
        int x = i % cols;
        int y = i / cols;
        if (x == lines + 1)
            System.out.println();
        else if (x + y < lines)
            System.out.print(' ');
        else
            System.out.print(cols - x - 1);
    }
}

prints

     1
    21
   321
  4321
 54321


class Series
{
    public static void main()
    {
        int i,j,k;
        for(i=1;i<=5;i++)
        {
            for(j=5;j>=i;j--)
            System.out.print(" ");
            for(k=i;k>=1;k--)
            System.out.print(k);
            System.out.println();
        }
    }
}


Click here for better understanding Java Number Pattern

public class Program {
    public static void main(String[] args) {
        
        //declare the size
        //change the size
        int size = 5;
        
        //use two loops
        //outer loop to set the number of iterations i.e size
        for(int i=1; i<=size; i++){
            //use inner loop with a limit
            for(int j=1; j<=i; j++){
                System.out.print(""+j);
            }
            //use print statement with println to print in next line
            System.out.println("");
        }
        //run the program
       
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜