I am supposed to write a method that scrambles a word, switching two letters in a word that is not the first or last character.
I've initialized i and j as random integers between positions 1 and str.length() -1. Is there a reason why this loop would not print the scrambled version of a word?
char[] chararray = word.toCharArray();
int i = (int) (Math.random() * ((word.length()-2) - (1)) + 1);
int j = (int) (Math.random() * ((word.length()-2) - (1)) + 1);
for (int x = 0; x < word.length(); x++)
{
if (x == i)
{
chararray[x] = word.charAt(i);
}
else if (x == j)
{
chararray[x] = word.charAt(j);
}
}
word = new String (chararray);
System.out.println(word);
When I input tofu
it would reprint tofu
. I'd like to input "tofu" and have it output "tfou".
I think you would be looking for the following
Interchange the i and j values in the if and else blocks.
when x equals i you are assigning the same value back in the chararray, hence you are getting the same value. But your intention is to interchange the character in i and j positions I hope.
And one more thing, make sure i never equals to j