0
import java.util.Scanner;
public class StringRotator {

public static void main(String[] args) {
    Scanner Scanner =  new Scanner(System.in);  
    System.out.println("Enter String");
    String str = Scanner.next();
    System.out.println("How many letters should be rotated?");
    int rt = Scanner.nextInt();
//Breaks apart string into a character array
    char[] array = str.toCharArray();
    int j  = 0;
    int l  = 0;
            //The while loop below takes each latter of the array and moves it up the specified number of times
    while (j > -rt) {
    array[array.length+j-1] = array[array.length+j-2];
    j = j-1;
    }
//This while loop takes the last letter of the string and places it at the very beginning. This is where the problem occurs.
    while (l < rt) {
        array[array[l]] = array[array.length];
    l = l + 1;
    }
//Recombines and prints the new string
    String complete  = array.toString();
    System.out.println(complete);
    }

}

I am trying to make a program in which when given a string such as abc, it will take the last letter of the string and "rotate" it to the front a specified number of times. It is all working well, except for line 18, which is throwing weird exceptions. For example. When I say the string is abc and to rotate it two times, although in Eclipse Debug it says the array length is 3, the line throws an exception saying its supposed to get a character from the 97th spot, even though it is supposed to get the character from the array.length spot or less, depending on the input. How is this happening?

Rohit M
  • 21
  • 1
  • `array[array.length]` will give you `ArrayIndexOutOfBoundsException` – Ramanlfc Dec 27 '15 at 19:46
  • Indexes in arrays starts from 0. So if array length is `3` its elements are indexed like `0` `1` `2`. Index `3` is out of that range/bounds. – Pshemo Dec 27 '15 at 19:48

2 Answers2

1

If this is a character:

array[l]

Then it sounds like this is using the numeric value of that character as the index:

array[array[l]]

It's not really clear why you'd want to do that. But taking a look at the ASCII table shows that a is 97, so that would explain why it's looking for that index.

You should be indexing between 0 and the length of the array (or, well, one less than the length), not with character values which could be outside the bounds of the array.

David
  • 208,112
  • 36
  • 198
  • 279
0

Remember, array indexing starts at 0, and since array.length returns the length of the array, to get the last index of the array, you need to subtract 1 since the indexing starts at 0. So subtract 1 from array.length.

Mario Ishac
  • 5,060
  • 3
  • 21
  • 52