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);
}
}
我试图在其中给出一个字符串,如ABC当一个程序,将采取字符串的最后一个字母和“旋转”它前面的指定次数。这一切都运行良好,除了第18行,这是抛出奇怪的例外。例如。当我说这个字符串是abc并且将它旋转了两次时,虽然在Eclipse Debug中它说数组长度是3,但该行会抛出一个异常,表示它应该从第97位获得一个字符,即使它应该得到来自array.length点或更少的字符,取决于输入。这是怎么发生的?数组运算抛出奇怪异常
'array [array.length]'会给你'ArrayIndexOutOfBoundsException' – Ramanlfc
数组中的索引从0开始。所以如果数组长度为3,它的元素索引为'0''1'' 2'。索引'3'超出了该范围/界限。 – Pshemo