I made a for loop to swap two indiv char variables in a string

1.3k views Asked by At

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".

3

There are 3 answers

4
HJK On BEST ANSWER

I think you would be looking for the following

 for (int x = 0; x < word.length(); x++) 
    {
        if (x == i) 
        {
             chararray[x] = word.charAt(j);
        }
        else if (x == j)
        {
            chararray[x] = word.charAt(i);
        }
    }

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

0
almightyGOSU On

Start with an character array.
Use a random generator to get 2 integers between 0 (inclusive) and length of character array (exclusive).

If i != j, swap them. (No point swapping a character with itself)

public class QuickTester {

    public static void main(String[] args) {

        Random rand = new Random();

        char[] charArr = "elephant".toCharArray();

        // Using charArr.length - 2 + 1 to exclude first and last
        int i = rand.nextInt(charArr.length - 2) + 1;
        int j = rand.nextInt(charArr.length - 2) + 1;

        if (i != j) {
            System.out.printf("Going to swap %c at position %d "
                    + "with %c at position %d%n", charArr[i], i, charArr[j], j);

            char temp = charArr[i];
            charArr[i] = charArr[j];
            charArr[j] = temp;

            System.out.println("\nResult: " + new String(charArr));
        }
    }
}

Result:

Going to swap t at position 7 with e at position 2

Result: eltphane

Update:

Changed from charArr.length to charArr.length - 2 + 1 to exclude first and last character.

1
Ankur Singhal On

Your logic seems to be wrong,

 if (x == i) 
        {
             chararray[x] = word.charAt(i);
        }

The above will just point to same index, both x and i points to same, you need to interchange the indexes.

Below code

public static void main(String args[]) {
        String word = "ankur";
        char[] chararray = word.toCharArray();
        int i = (int) (Math.random() * ((word.length() - 2) - (1)) + 1);
        int j = (int) (Math.random() * ((word.length() - 2) - (1)) + 1);
        System.out.println(i + " and " + j);
        for (int x = 0 ; x < word.length() ; x++) {
            if (x == i) {
                chararray[x] = word.charAt(j);
            } else if (x == j) {
                chararray[x] = word.charAt(i);
            }
        }

        word = new String(chararray);
        System.out.println(word);
    }

output

2 and 1
aknur