Yan
Yan

Reputation: 77

How to print strings in multiple lines in a decreasing order?

I'm using Java 8 and I need to get this output:
XXXXX
XXXX
XXX
XX
X

where "X" is a string.

I wrote a simple code:

String s = new String ("X");  
int j = 5;
for (int i = 0; i<5; i--)
{
    System.out.println(s);
j--;

    if (j < 1) 
            break;

Naturally, get this:

X
X
X
X
X

I understand that I need to somehow make Java repeat printing the string i times (in a loop I assigned for i), but don't know how (neither repeat nor \i didn't work). What's the best way to do it? Thanks!

Upvotes: 2

Views: 330

Answers (4)

Ibrahim.H
Ibrahim.H

Reputation: 1195

concat here is another option:

String s = "";
for (int i = 5; i>0; i--) {
    String s1 = "";
    for (int j = i; j > 0; j--){
        s1 += s.concat("X");
    }
    System.out.println(s1);
}

Upvotes: 0

Vikas
Vikas

Reputation: 7175

You can use while loop inside for

  String s = "X";
    for (int i = 5; i > 0; i--) {
        int j=0;
        while(i>j++)
            System.out.print(s);
        System.out.println();
   }

Upvotes: 0

Nicholas K
Nicholas K

Reputation: 15423

All you need to do is:

final String s = "X";
for (int i = 5; i > 0; i--) {
    for (int j = 0; j < i; j++) {
        System.out.print(s);
    }
    System.out.println();
}

which outputs:

XXXXX

XXXX

XXX

XX

X

Upvotes: 3

gbryce
gbryce

Reputation: 56

You can use a recursive print operation to achieve this without loops.

import java.util.Collections;

public class Test {

public static void main(final String[] args) {
    recursiveTriangle(10);
}

public static void recursiveTriangle(final int length) {
    if (length <= 0 ) {
        return;
    }

    System.out.println(String.join("", Collections.nCopies(length, "X")));

    recursiveTriangle(length-1);
}

}

Upvotes: 0

Related Questions