I have been trying different things for a while now and I can't figure out why my logic is wrong. It isn't making sense.
I am trying to make a program based on the following pseudocode.
Translate the following pseudocode for randomly permuting the characters in a string into a Java program.
- Read a word.
- Repeat the loop word.length() times
- Pick a random position i in the word, but not the last position.
- Pick a random position j > i in the word.
- Swap the letters at positions j and i.
- Print the word.
- Then replace the string with:
first + word.charAt(j) + middle + word.charAt(i) + last
This is what I have so far:
package assignment4;
import java.util.Scanner;
public class P4Point7 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter a word: ");
String word = in.next();
in.close();
int wordLength = word.length(); // Gets the word.Length
int x = 1; // Primes the loop
while (x <= wordLength) {
int i = (int) ((Math.random() * wordLength) - 1); // Gets a random letter i that is not the last letter
int j = (int) (Math.random() * (wordLength - i)) + i; // Gets a random letter j after i
String first = word.substring(0, i); // Gets first part of word
String middle = word.substring(i + 1, j); // Gets middle part of word
String last = word.substring(j + 1, wordLength); // Gets last part of word
x++; // Increments the loop
String status = first + word.charAt(j) + middle + word.charAt(i) + last; // Swaps i and j in the word
System.out.println(status);
}
}
}
The problem I am having is
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at assignment4.P4Point7.main(P4Point7.java:21)
I am testing the program with the word "Waffle".