我正在尝试编写一个基本的java程序,它从Excel电子表格中收集数据并将其存储在数组中。我遇到的问题是我收到 ArrayOutOfBounds 异常,但看不到我超出数组范围的位置。我什至故意将数组的尺寸设置为明显大于循环终止值:
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class InputArray {
public static void main(String[] args) {
String[][] InputArray1;
int i = 0;
int j = 0;
InputArray1 = new String[220][220];
try{
Workbook OLE1Shots = Workbook.getWorkbook(new File("C:/Book12.xls"));
Sheet inList = OLE1Shots.getSheet(0);
for (i = 0; i < 190; i++){
Cell aCell = inList.getCell(i, 0);
Cell bCell = inList.getCell(i, 1);
String strIn = aCell.getContents();
String strOrd = bCell.getContents();
if (strIn != ""){
InputArray1[0][j] = strIn;
InputArray1[1][j] = strOrd;
j = j + 1;
}
}
}
catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (i = 0; i < 190; i++){
System.out.println(InputArray1[0][i]);
System.out.println(InputArray1[1][i]);
}
}
}
我收到的完整消息是:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at jxl.read.biff.SheetImpl.getCell(SheetImpl.java:356)
at InputArray.main(InputArray.java:29)
如果有人能找出这里出了什么问题,那就太好了。希望这只是我的愚蠢。
编辑:
我做了一些愚蠢的事情。引发错误的原因是我对单元格位置(行、列)使用了 VBA 表示法,而 jxl 使用(列、行)。我更改了这些行:
for (i = 0; i < 190; i++){
Cell aCell = inList.getCell(i, 0);
Cell bCell = inList.getCell(i, 1);
致这些:
c = inList.getRows();
for (i = 0; i < c; i++){
Cell aCell = inList.getCell(0, i);
Cell bCell = inList.getCell(1, i);
代码现在运行并正确打印出字符串。但是,我确实不断收到消息
InputArray as localhost contains obsolete methods. The virtual machine was unable to remove all stack frames running old code from the call stack...
最佳答案
您的变量“i”从 0 到 189,并被提供给从电子表格读取单元格的方法。电子表格有那么多行吗?请注意,电子表格程序中出现的行并不一定意味着电子表格文件中也存在这些行。
这条消息准确地(如果不是完全的话)告诉您出了什么问题——太大的索引是“2”,报告错误的方法是getCell()
,行号告诉您错误发生在程序的哪个位置。
关于java.lang.ArrayIndexOutOfBoundsException : Having difficulty working out where error occurs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21216432/