java - 类的实例导致 nullPointerException

标签 java eclipse excel

我正在 Eclipse 中使用 poi 导入 Excel 2007 文件。我的问题是 NullPointerException ,但我不知道如何弄清楚它来自哪里。也许类 Data 的实例有问题。这是代码:

import java.io.*;
import java.io.*;
import java.util.ArrayList;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.xmlbeans.XmlOptions;

class Data{
    public Data(){};
    public Data(double[] codnt, int ctgr1, int ctgr2) {
    //  super();
        this.codnt = codnt;
        this.ctgr1 = ctgr1;
        this.ctgr2 = ctgr2;
    }
    double codnt[];
    int ctgr1;
    int ctgr2;  
}
class Center{
    public Center(int cycle, Data[] c) {
//      super();
        this.cycle = cycle;
        this.c = c;
    }
    int cycle;
    Data c[];
}
public class KmeansCluster {
    @SuppressWarnings({ "static-access", "null" })
    public static void main(String[] args)throws IOException,InvalidFormatException{
        InputStream is = new FileInputStream(new File("src//artificial_exp1.xlsx"));
        Workbook wb = WorkbookFactory.create(is);
        Sheet sheet = wb.getSheetAt(0);
        ArrayList<Data> list = new ArrayList<Data>();
        int i = 0;
        try {
            for (Row row : sheet) {
                Data dataTemp = new Data();
                // int i = 0;
                int j = 0;
                for (Cell cell : row) {
                    row.getCell(0).setCellType(cell.CELL_TYPE_NUMERIC);
                    dataTemp.codnt[j] = cell.getNumericCellValue(); 
                                  j++;
                    System.out.println("cell.getnumericcellvalue() is " + cell.getNumericCellValue() + "datatemp.condt[j] is " + dataTemp.codnt[j]);
                    System.out.println(" test passed !");
                }
                dataTemp.ctgr1 = (int) dataTemp.codnt[j - 2];
                dataTemp.ctgr2 = (int) dataTemp.codnt[j - 1];
                list.add(dataTemp);
                i++;
            }
            Data data1 = (Data) list.get(0);
            System.out.println(data1.codnt[0]
                    + "    is the content of the first blank.");
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }

}

最佳答案

Data 的无参构造函数使 codnt 未初始化。您可以通过在通用异常 block 中打印堆栈跟踪来找到这一点

关于java - 类的实例导致 nullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29473418/

相关文章:

excel - 如何编写excel公式以返回列标题名称

java - 是否有必要在构造函数中指定每个 Java 类的属性?

Excel:如果一个单元格包含两个单词,我将如何使用第一个单词的第一个字母和第二个单词的前两个字母?

java - 如何更改Spring Cloud GCP的依赖版本

eclipse - 移动eclipse的默认配置文件夹

java - 使用 java 从 Maven 多模块项目创建 war 文件失败

css - Eclipse 中 Javadoc 的自定义样式

excel - VBA计算范围内的单元格数量

java - QuickFIX/J 如何禁用自动登录响应

java - 端口 8005 Tomcat 需要,已被占用