String jumble(String): accepts a string and returns a jumbled version of the original: for this method, jumbled
means that two randomly chosen characters other than the first and last characters of the string are swapped; this method
must use the class, Random. The method must swap two different characters: in other words the two random
indices into the string cannot be equal, cannot be 0, and cannot be equal to the string’s length minus one. So, for example, a
four-letter string MUST result in the returned string having the same first and last characters and have the second and third
characters swapped. Examples of what this method might do: “fist” returns “fsit”, “much” returns “mcuh”, but for longer
strings there will be more possible return values: “spill” could return “splil” or “sipll”. Only ONE pair of letters should be
swapped and strings shorter than four characters are returned unchanged. When the string length is greater than 3, the
original string must never be returned.
I cant seem to get the first and last character to stay the same. It will always scramble the whole word.
DO NOT USE ANY CLASSES only random.
Im a BEGINNER so keep it Easy talk no Array's, appends, etc.
Use substrings, CharAt, length only. if and else for loops are fine while loops are also okay aswell as do/while.
public class Test {
public static void main(String[] args) {
String s = "goal";
System.out.print(jumble(s));
}
public static String jumble(String s) {
int i = 0;
int b = s.length() -1;
String result = "";
java.util.Random r;
r = new java.util.Random();
char beginning = s.charAt(0);
char ending = s.charAt(s.length() - 1);
if ( r.nextBoolean() ) {
result = beginning + result + s.substring(1, b) + ending;
}
else{
result += beginning + s.substring(1, b)+ ending;
}
return result;
}
}