If I enter the string str and int n, I need to create a loop that will print the beginning of the line n times, with the first n characters, then the first n - 1, then n - 2, and so on, until it prints only the first character.
So, for example, "Apples" and "3" will lead to "AppApA".
I created the following that works ... several. "n" is an int.
int i = 0;
while(i <= n)
{
System.out.println(str.substring(0, Math.min(str.length(), n)));
n = n - 1;
i++;
}
This works for ints <= 2; if I enter a string like "Chocolate" and int 3, I get "ChoCh" when I get "ChoChC".
It made me startle for about 30 minutes. Any insight appreciated.
wayoo source
share