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?