java中的ArrayIndexOutOfBoundsException

时间:2013-02-03 08:38:32

标签: java arrays

import java.io.*;
import java.util.Scanner;

public class ws1qn2 
{

    public static void main(String[] args) throws IOException
    {
        Scanner input=new Scanner(System.in);
        int a;
        int d;
        System.out.println("Please enter the number of characters the word has: ");
        d=input.nextInt();
        a=d-1;
        char word[]=new char[a];
        for (int b=0;b!=a;b++)
        {
            System.out.println("Please enter character no."+b+1);
            String str;
            str=input.next();
            char c=str.charAt(b);
            word[a-b]=c;
        }
        for (char reverse : word)
        {
            System.out.print(reverse);
        }
    }
}

以下是我运行程序时会发生的事情:

Please enter the number of characters the word has: 
3
Please enter character no.01
s
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at ws1qn2.main(ws1qn2.java:22)

Process completed.

帮助?它看起来像堆栈溢出,但我不知道如何解决它。

2 个答案:

答案 0 :(得分:1)

您的问题如下:您正在将word初始化为长度为d-1的数组,在您的情况下为2,但Java Arrays为0索引,因此长度为2的数组仅上升到索引1:

然后您尝试访问word[2]以将其设置为c,这会使您的数组索引超出范围

答案 1 :(得分:1)

每次都会读取

str,并且它的大小似乎应该是1.你不应该这样做char c=str.charAt(b);但是你应该总是得到他的第一个字符char c=str.charAt(0);

b为零时的另一个问题,a-ba,因此words[a-b]超出了大小为words的数组a的范围。您应该从索引中减去1:words[a-b-1]