我是java编程和新手; selenium并使用jxl-2.6.12.jar文件学习Jxl概念。在尝试将excel工作表单元格中的值赋给String数组变量时,我在以下代码中收到错误。字符串数组变量值为null,导致NULLpointerException错误。
代码中的问题是:::::
if ( sht[0].getCell(3, rowIteration).getContents() == "Y")
{ arrString[arrIndex] = sht[0].getCell(1, rowIteration).getContents();
System.out.println(arrString[arrIndex]);
}
完整代码是::::::
package excellearning;
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class ExcelLearning {
ExcelLearning xl = new ExcelLearning();
public static void main(String[] args)throws IOException,BiffException {
//ExcelLearning xlObject = new ExcelLearning();
xlLearning();
}
方法1 :::::
public static void xlLearning() throws ArrayIndexOutOfBoundsException, BiffException, IOException {
Sheet sht[] = null;
String[] arrString = new String[20];
sht = get_Data_From_Excel();
Cell baseRowCell, dataRowCell;
int rowCount = sht[0].getRows();
int colCount = sht[0].getColumns();
System.out.println (rowCount + " " + colCount);
boolean flag = false;
int colIteration = 0 , rowIteration = 1, arrIndex = 0;
//String str=null;
while(rowIteration < rowCount)
{
if ( sht[0].getCell(3, rowIteration).getContents() == "Y")
{ arrString[arrIndex] = sht[0].getCell(1, rowIteration).getContents();
System.out.println(arrString[arrIndex]);
}
rowIteration++;
arrIndex ++;
}
int length = arrString.length;
for(arrIndex=0; arrIndex<length; arrIndex++)
{
System.out.println(arrString[arrIndex].toString());
}
}
方法2 :::::
public static Sheet[] get_Data_From_Excel()throws BiffException, IOException
{ Workbook wrk1;
Sheet sheet1[] = null;
try {
wrk1 = Workbook.getWorkbook(new File("D:/Mercury_Master.xls"));
sheet1 = wrk1.getSheets();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sheet1;
}
}
你可以告诉我为什么会发生这种情况,因为我无法找到根本原因吗?
这是工作表的屏幕截图:::
答案 0 :(得分:0)
sht[0].getCell(1, rowIteration).getContents()
可以返回null。在这些情况下,arrString[arrIndex]
也将为空。在这些情况下,您可以将它设置为空String,或者在对它执行任何操作之前显式检查null。
如果为null,则此代码将抛出NPE:
System.out.println(arrString[arrIndex].toString());
虽然这段代码应该没问题:
System.out.println(arrString[arrIndex]);
只需打印null。