user1707517
user1707517

Reputation: 35

java for loop pyramid

I want to create a loop with a string so that with each successive loop, the last and first characters from the previous line will not be displayed. I'm also trying to print the length of each loop next to each line. It will look like an upside-down pyramid.

I had this:

    for(int scounter = fullName.length(); scounter > 0; scounter--)
    for (String name : fullName)
    for(int counter = 0; counter < fullName.length(); counter++)

     System.out.println(scounter + "[ " + fullName.substring(0, fullName.length() counter)+ " ]");

It prints something like this:

   24******
   24****
   24**
   24*

Yet I'm looking for something similar to this:

    7*******
     5*****
      4***
       1*

Upvotes: 0

Views: 1939

Answers (4)

    for(int i = 1; i<=4; i++) {
        for(int k = 3;k>=i; k--){
                System.out.print(" ");
            }
    for(int j = 1; j<=i; j++){
            System.out.print("*");
        }
        for(int n = 2; n<=i;n++){
            System.out.print("*");
        }   
                        
        System.out.println(" ");
    }
        for(int m = 1 ;m<=3; m++){
            for(int o = 1;o<=m; o++){
                System.out.print(" ");
            }
            for(int p = 3;p>=m;p--){
                System.out.print("*");
            }
            for(int q = 2;q>=m;q--){
                System.out.print("*");      
            }   
            
            System.out.println();
        }   
}

}

Upvotes: 0

Anand V
Anand V

Reputation: 124

I started working on this problem and found my solution to be slightly different from Joao's. Hope this helps!

public class pyramid
{

public static void main(String[] args)
{
    for(int i=0, sz=args[0].length();i<sz; ++i,--sz)
    {
      System.out.printf("%"+(i+1)+"d%s\n", sz-i, args[0].substring(i,sz));
    }
}

}

Invocation as per request:

java pyramid abcdefg
7abcdefg
 5bcdef
  3cde
   1d

java pyramid abcdef
6abcdef
 4bcde
  2cd

Upvotes: 1

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91299

String str = "*******";
for (int i = 0, l = str.length(); i <= l/2; i++) {
  String line = str.substring(i, l - i);
  System.out.printf("%" + (i + 1) + "d%s\n", line.length(), line);
}

This will print:

7*******
 5*****
  3***
   1*

I'm assuming you meant 3 instead of 4 in your example, that is, that you want to decrement by 2.

Upvotes: 2

Ted Hopp
Ted Hopp

Reputation: 234795

Your example does not match the words of your question, so here's a method that behaves according to your words as I understand them:

public void pyramid(String text) {
    int len = text.length();
    int start = 0;
    while (start < len) {
        for (int i = 0; i < start; ++i) {
            System.out.print(" ");
        }
        System.out.println(text.substring(start, len));
        ++start;
        --len;
    }
}

Upvotes: 0

Related Questions