2013-02-03 174 views
-2
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); 
     } 
    } 
} 

這是當我運行該程序會發生什麼:ArrayIndexOutOfBoundsException異常在Java

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. 

幫助?它看起來像一個堆棧溢出,但我不知道如何解決它。

+3

看起來像一個'ArrayIndexOutOfBoundsException'給我... –

+0

是的..我想知道這是如何堆棧溢出.. –

回答

1

你的問題如下:你初始化字是長度d-1的數組,你的情況2,但是,Java數組索引0這樣長度爲2的數組只上升到指數1:

然後您嘗試訪問word[2]將其設置爲c,驅動你的數組索引越界

+0

另外我覺得一個ouotOfBounds將在這裏拋出'char c = str.charAt(b);'。 –

1

str的每次讀取,其大小似乎有望成爲1.你不應該這樣做char c=str.charAt(b);,而是你應該總是讓他第一個字符char c=str.charAt(0);

b是零時的另一個問題,a-ba,因此words[a-b]超出了大小爲a的數組words的界限。你應該從這裏索引減1:words[a-b-1]

相關問題