0

I'm attempting to scramble two random letters of a string which isn't the first letter, or last two. I'm getting a "String index out of range" error when compiling. I've tried workshopping many different solutions, but nothing seems to work.

For this assignment, we have to use a method and .charAt commands. I've tried creating variables for the two random characters then adding them back into the string flipped, but couldn't get that to work either.

public static String scramble(String input) {
    int range = input.length() - 3;
    int place = (int)(Math.random() * range);
    String newWord = "";
    newWord = input.substring(0, place);
    newWord = newWord + newWord.charAt(place) + 2;
    newWord = newWord + newWord.charAt(place) + 1;

    return newWord;

I'm expecting an output of a string with two of its characters scrambled. For example, "Fantastic" would be "Fantsatic", or "Fnatastic".

TalBZ
  • 13
  • 2

4 Answers4

0

You do :

newWord = input.substring(0, place);

So the indexes inside newWord goes from 0 to place-1
Then you do:

newWord.charAt(place);

But this index does not exist in your String. It is Out of Bound

See the doc

vincrichaud
  • 2,218
  • 17
  • 34
0

When you create newWord = input.substring(0, place) it has exactly place characters. You can't request charAt(place) from it, the last character is at place-1.

If you want to swap characters convert input to char[] and generate random indexes to swap.

String input = "Fantastic";

// random constraints
int min = 1;
int max = input.length() - 3;

// random two characters to swap
int from = min + (int) (Math.random() * max);
int to;
do {
    to = min + (int) (Math.random() * max);
} while (to == from); // to and from are different

// swap to and from in chars
char[] chars = input.toCharArray();
char tmp = chars[from];
chars[from] = chars[to];
chars[to] = tmp;
String result = new String(chars);

System.out.println(result); // Ftntasaic
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
0

you can try

  public static String scramble(String input) {
    if(input.length() >3){
        int range = input.length() - 3;
        int place  = 1+   new Random().nextInt(range) ;
        input=input.substring(0, place) +input.charAt(place  + 1)+input.charAt(place) +input.substring( place+2);

    }
    return input;
}

input: Fantastic output : Fanatstic , Fatnastic ,Fanatstic

Rupesh Agrawal
  • 645
  • 8
  • 22
0

Try something like this:

public static String scramble(String input) {
    int range = input.length() - 3;
    int place = (int)(Math.random() * range);
    String newWord = input.substring(0, place);
    newWord = newWord + input.charAt(place + 1);
    newWord = newWord + input.charAt(place);
    // if you need the whole input, just 2 characters exchanged, uncomment this next line
    // newWord = newWord + input.substring(place + 2, range);
    return newWord;
}
Usagi Miyamoto
  • 6,196
  • 1
  • 19
  • 33