scrambleWord and scrambleOrRemove is #1 from the from the 2014 AP Computer Science A Free Response problems.

Part (a) scrambleWord method

public static String scrambleWord(String word)
    String scrambledWord = word;
    int i = 1;
    while(i < scrambledWord.length())
        if("A".equals(scrambledWord.substring(i - 1, i)) &&
                ! "A".equals(scrambledWord.substring(i, i + 1)))
            scrambledWord =
                    scrambledWord.substring(0, i - 1) +
                    scrambledWord.substring(i, i + 1) +
                    "A" +
                    scrambledWord.substring(i + 1);
            i += 2;
    return scrambledWord;

Although String objects are immutable, it is possible to pretend that they are mutable by making a new String object and setting the existing variable to point to it. This approach makes this problem much simpler.

See Strings on the AP CS A Exam for an explanation of String methods and String concatenation.

An alternative approach is to build a new String by concatenating parts of the existing String. This is difficult here, especially with respect to the end of the new String.

A recursive approach is also reasonable here.

Part (b) scrambleOrRemove method

public static void scrambleOrRemove(List<String> wordList)
    for(int i = wordList.size() - 1; i >= 0; i--)
        String scrambled = scrambleWord(wordList.get(i));
            wordList.set(i, scrambled);

See ArrayList practice for details on adding to and removing from an ArrayList within a loop.

2014 AP CS Exam Free Response Solutions

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on scrambleWord