How do I repeat a string where each character is repeated a decreasing number of times?

Tags:



Ah yes, I am back with another Java question. So here I am supposed to repeat a string where its characters repeat a decreasing number of times. The first character should be repeated the string’s length number of times.

Here is an example of what the output should look like:

HHHHH
oooo
www
dd
y

What should I do next based on the code I have written below?

String go( String a) 
{
  String y = "";
  for (int i = 0; i < a.length(); i++)
  {
    for (int j = 0; j < a.length(); j++)
    {
      y = y + a.charAt(i);
    }
    if (i == a.length() - 1)
    {
      y = y + "";
    }
    else
    {
      y = y + "n";
    }
  }
  return y;
}

Feel free to point out any obvious mistakes I have made. I am new to Java and just learned that Java and Javascript are not the same thing!

Answer

When I ran the code you posted in your question, I got this result:

HHHHH
ooooo
wwwww
ddddd
yyyyy

which is not what you want.
In order to get what you want, you simply need to make one change in your code. You need to change the inner for loop. Here is your code with the required addition.

private static String go(String a) {
    String y = "";
    for (int i = 0; i < a.length(); i++) {
        for (int j = 0; j < a.length() - i; j++) { // change here
            y = y + a.charAt(i);
        }
        if (i == a.length() - 1) {
            y = y + "";
        }
        else {
            y = y + "n";
        }
    }
    return y;        
}

When you run that code, it produces the following output.

HHHHH
oooo
www
dd
y

which is what you want, isn’t it?



Source: stackoverflow