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