数组操作抛出奇怪的异常

时间:2015-12-27 19:44:37

标签: java arrays

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时,它将取字符串的最后一个字母并且&#34;旋转&#34;它在前面指定的次数。这一切都运作良好,除了第18行,这是一个奇怪的例外。例如。当我说字符串是abc并将其旋转两次时,尽管在Eclipse Debug中它表示数组长度为3,该行抛出一个异常,说它应该从第97个点获得一个字符,即使它应该得到array.length spot或更少的字符,具体取决于输入。这是怎么回事?

2 个答案:

答案 0 :(得分:1)

如果这是一个角色:

array[l]

然后听起来这是使用该字符的数值作为索引:

array[array[l]]

为什么你想这样做并不是很清楚。但是,查看ASCII table表明a97,这样可以解释为什么它会查找该索引。

你应该在0和数组的长度之间建立索引(或者,一个小于长度的索引),而不是字符值可能超出数组的范围。

答案 1 :(得分:0)

请记住,数组索引从0开始,并且由于array.length返回数组的长度,要获取数组的最后一个索引,因此需要从索引中减去10开始。因此,从1中减去array.length

相关问题