2015-04-05 42 views
-1
public static void getImage() throws FileNotFoundException 
{ 
    Scanner input = new Scanner(new File(fileName)); 
    String element = input.nextLine();// 

    // tokenize string with " " as the delimiter 
    StringTokenizer tokenizer = new StringTokenizer(element, " "); 

    // store y and x variables 
    imageHeight = Integer.parseInt(tokenizer.nextToken()); 
    imageWidth = Integer.parseInt(tokenizer.nextToken()); 
    System.out.println(imageHeight); 
    System.out.println(imageWidth); 

    buffer = new char[100] [100]; 
    System.out.println("Getting Image ..."); 


for (int i = 0; i < imageHeight; i++) 
{ 

    element = input.nextLine(); 
    for (int j = 0; j < imageWidth; j++) 
    { 

    buffer[i][j] = element.charAt(j); 

    } 

} 

    input.close(); 

} 

整個代碼編譯但上面是整個代碼的一部分,當我運行它時給了我錯誤。代碼的目標是創建一個多維數組,當它打印出來時,它會在文本文件中顯示由字符組成的圖像。它通過解析指定的.txt文件來獲取索引。前2個讀取令牌是定義數組大小的數字。然後繼續讀取.txt文件,並將字符分配到原始文本文件中的位置,最終創建由字符組成的圖像。對.charAt()的OutOfBoundsException,尋找解釋

這部分代碼應該將文件中的所有字符放入數組中,但即時獲取運行錯誤。請幫忙!

+2

你的鹼的假設是,'element'具有相同的長度爲'imageWidth' - 添加調試印刷,可測試此假設是真的;) – alfasin 2015-04-05 04:21:26

+0

時imageWidth是這可能發生更多的元素字符可以顯示計算代碼imageWidth – 2015-04-05 04:25:53

+0

我添加了前面的代碼。獲取imageWidth大小的方法是讀取用戶以前指定的.txt文件中的第二個數字。 – 2015-04-05 04:54:32

回答

0

您試圖在空位置獲取char。在訪問特定位置(j)之前添加一些驗證。

element.lenght()> 0