Lory A Lory A - 2 months ago 16
Java Question

Rotate between colors in String

I'm trying to create a

that rotates color. Every letter has a different
, and they need to rotate in a linear manner. The text will go inside of a

I built the text so that it could be created given a word and an array of colors (Strings).

String[] colors = {"white", "blue", "red"};
String word = "foo";
String coloredText;

String[] letters = word.split("(?!^)"); //split text into indiv. letters

coloredText = "<html>";

for(int i = 0, j = 0; i < letters.length; i++, j++){

if(j >= colors.length)

coloredText += String.format("<font color='%s'> %s </font>", colors[j], letters[i]);

coloredText += "</html>";

This will result in a string that has foo with a white
, blue
and red final

Of course if there were less colors than letters, they would just keep on rotating.

Now I have a
to rotate the colors, but I can't figure out the
to do it.
Basically, every color should take the place of the following one, with the last one replacing the first.

So for example:

enter image description here

Of course this has to work for any number of given letters and colors, with the colors that don't fit being ignored. (A word of 3 letters with 10 colors will only use the first 3 colors).

I have tried using
is a bit too difficult for me.

Any idea?


You can have an additional integer (class or instance variable, depending on your code) as an offset counter between 0 and colors.length-1.

int offset = 0

Every time your timer executes, increment the offset by 1 and check if your offset overflows the allowed offset. If so, reset it to 0.

void onTimerExecutes(){
    if (offset >= colors.length)
        offset = 0;

Then add the offset to your j:

j = offset;
for(int i = 0, i < letters.length; i++, j++)