2015-12-27 71 views
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); 
    } 

} 

我试图在其中给出一个字符串,如ABC当一个程序,将采取字符串的最后一个字母和“旋转”它前面的指定次数。这一切都运行良好,除了第18行,这是抛出奇怪的例外。例如。当我说这个字符串是abc并且将它旋转了两次时,虽然在Eclipse Debug中它说数组长度是3,但该行会抛出一个异常,表示它应该从第97位获得一个字符,即使它应该得到来自array.length点或更少的字符,取决于输入。这是怎么发生的?数组运算抛出奇怪异常

+0

'array [array.length]'会给你'ArrayIndexOutOfBoundsException' – Ramanlfc

+0

数组中的索引从0开始。所以如果数组长度为3,它的元素索引为'0''1'' 2'。索引'3'超出了该范围/界限。 – Pshemo

回答

0

记住,数组索引开始于0,由于array.length返回数组的长度,以获取数组的最后一个索引,你需要减去1因为索引开始于0。所以从array.length减去1

1

如果这是一个字符:

array[l] 

然后,它听起来就好像是使用字符作为该指数的数值:

array[array[l]] 

这不是真的清楚为什么你要要做到这一点。但看看ASCII table显示a97,所以这将解释为什么它正在寻找该指数。

您应该在0和数组长度之间进行索引(或者,小于长度的一个长度),而不是使用可能超出数组边界的字符值。

+0

啊,谢谢。删除额外的数组块工作。 –