So i've got a for loop that's reversing every other word in a string. I can't determine which condition is causing this. I've spent a good amount of time staring at this and the API, to no avail. Anyone have any idea why it's not working?

String newMessage;
    StringBuilder stringBuilder = new StringBuilder();
    newMessage = messageToEncrypt.replaceAll("[^0-9a-zA-z\\s]",""); //check for a non-word character
    String[] words = newMessage.split("\\s"); // Array to split the words into each index
    for (int i = 0; i < words.length; i++) 
    {
        stringBuilder.append(words[(words.length-1)-i]);
        stringBuilder.reverse();
        //stringBuilder.append(words[words.length-1]);
        stringBuilder.append(" ");

    }
    newMessage = stringBuilder.toString();
    return newMessage;

Every time you append a word you reverse the entire string, so the last word is reversed once, the previous word is reversed twice, the word before that is reversed 3 times, ... , and the first word is reversed (words.length) times. Of couse an even number of reversals is the same as not reversing.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.