The trouble is in this code block:
if((start+1) - randomPos <= 1) {
eachWord = text.substring(randomPos , whiteSpace-1);
} else if((whiteSpace-1) - randomPos <= 1) {
eachWord = text.substring(start+1 , randomPos);
} else {
eachWord = text.substring(start+1 , randomPos) +
text.substring(randomPos , whiteSpace-1);
}
Trying to penetrate this makes my head hurt.
I replaced it with this:
String scrambled = scramble(eachWord);
String scrambledWord = String.valueOf(first) + scrambled + last;
System.out.printf("scrambled = %s scrambledWord = %s%n",
scrambled, scrambledWord);
and it works okay so far. The
scramble method calls another helper method. Breaking
things up like this makes everything easier to follow, understand and to troubleshoot. It
is an easy way to break down complex tasks into easy–to–manage steps. Your code block
above will have to deal with much more complexity to work properly. And since you want to
do this on your own I'll only say this: I found it much easier to build up a new String by
appending randomly–selected
chars from "eachWord".