Tyler P
Tyler P

Reputation: 147

How do I print a single character multiple times on one line?

Here's what I need to do:

In reverse order, print out the first num positive integers, with each integer being printed the number of times as its magnitude.

Basically, I'll use the number 9 as an example, I need to print 9 9's on one line, 8 8's on the second line, 7 7's, etc. all the way to 1.

I got it to print in reversed order but I don't know how I can print its magnitude. Here's my code now:

static void printReverse(int n) {

for (int reverse = n; reverse = 1; reverse--) {
  System.out.println(reverse);
}

System.out.println(); // Leaves space between the outputs
System.out.println();

Upvotes: 1

Views: 1588

Answers (4)

Felipe Cristiano
Felipe Cristiano

Reputation: 301

Java has a repeat function to build copies of a source string:

String newString = "a".repeat(N);
assertEquals(EXPECTED_STRING, newString);

This allows us to repeat single characters, or multi-character strings:

String newString = "-->".repeat(5);
assertEquals("-->-->-->-->-->", newString);

reference: https://www.baeldung.com/java-string-of-repeated-characters

Upvotes: 0

Michael S. Molina
Michael S. Molina

Reputation: 732

This function accepts an integer and in reverse order, print out each integer the number of times as its magnitude. The first loop takes care of decrementing the number and the second loop resolves the magnitude. Each number is printed in a new line.

static void printReverse(int n) {
   for (int i = n; i > 0; i--) {
       for (int j = 0; j < i; j++) {
           System.out.print(i + " ");
       }
       System.out.println();
   }
}

This is the output:

n n n ... (n times)
n-1 n-1 ... (n-1 times)
n-2 n-2 ... (n-2 times)
...
3 3 3
2 2
1

Upvotes: 1

leldo
leldo

Reputation: 386

If you run Java 11 there's a method "repeat" inherited from StringUtils I think :

static void printReverse(int n) {

for (int reverse = n; reverse = 1; reverse--) {
  System.out.println(String.valueOf(reverse).repeat(reverse));
}

Since there's a type conversion it's not faster than the double loop proposed but it's a one-liner 😊

Upvotes: 1

Krayzzee
Krayzzee

Reputation: 96

If you want to print everything in 1 line then you need to change from println to print. I added another for loop to print the numbers in one line and added the line break after this loop.

for (int reverse = 9; reverse >= 1; reverse--) {
  for (int i = 1; i <= reverse; i++)
    System.out.print(reverse);
  System.out.println();  // Line break after each number.
}

Output for the code above:

999999999
88888888
7777777
666666
55555
4444
333
22
1

I hope i understood clearly what you wanted.

Upvotes: 2

Related Questions