空指针异常

时间:2011-03-04 08:07:41

标签: java netbeans

我有两个类的代码

package myProva;

import java.io.*;
import java.util.StringTokenizer;
import java.util.*;
import java.text.SimpleDateFormat;

public class FileImport {

    private File fileToImport;

    public FileImport(File myFile) {
        fileToImport = myFile;
    }//constructor for fileToImport field

    int lines = 0;
    String[][]bin;

    public boolean checkIsFile(){
        return fileToImport.isFile();
    }

    public int numberOfLines(){
        lines = 0;
        if(checkIsFile()){
            try{
                FileReader fr = new FileReader(fileToImport);
                BufferedReader br = new BufferedReader(fr);
                while((br.readLine()!=null)){
                    lines++;
                }//end while loop
                br.close();
        }catch(Exception e){
                System.out.println(e);
            }
        }
          else{
               System.out.println("There is no file to import");
                }
        return lines;
        }//returns number of lines in a txt file

    public void importToArray(){
        int rows = 0;
        bin = new String[numberOfLines()][6];
        try {
             FileReader fr = new FileReader(fileToImport);
             BufferedReader br = new BufferedReader(fr);
             String line = null;

             while((line = br.readLine())!= null){
                 StringTokenizer stk = new StringTokenizer(line, ",");
                 while(stk.hasMoreTokens()){
                     for (int cls = 0;cls<6; cls++){
                         bin[rows][cls]= stk.nextToken();
                     }
                     rows++;
                 }//end inner while loop
             }//end outer while loop
             br.close();
        }//end try
        catch(Exception e){
            System.out.println(e);
        }
    }//import data to bin array

    public void printArray(){
        for(int i =0;i<bin.length; i++){
            System.out.printf("%s ", i);
            for(int j =0;j<bin[i].length; j++){
                System.out.printf("%s ", bin[i][j]);
            }
            System.out.println("");
        }//end for loop
    }//print contents of bin array

    public String[][] getArray(){
        return bin;
    }//return bin array

    double[][]dataArray = new double [numberOfLines()][5];//Array for double data
    Date[]dateArray = new Date[numberOfLines()];//Array for date(calendar)

    public void buildDateArray(String[][]d) {
       SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//set date format here
       for(int i=0;i<d.length; i++){
           for(int j = 0;j<d[i].length; j++){
               if(j==0){
                   try{
                       Date newDate = (Date)sdf.parse(d[i][0]);//parse first column to Date
                       dateArray[i] = newDate;
                   }//end try
               catch(Exception e){
                       System.out.println(e);
                   }//end catch
           }
       }
   }//end for loops
    }

    public void buildDataArray(String[][]d){
       for(int i=0;i<d.length;i++){
           for(int j=0;j<d[i].length; j++){
               switch(j){
                   case 0:
                       dataArray[i][j]=0;
                       break;
                  case 1:
                       dataArray[i][j]=new Double(d[i][j]);
                       break;
                  case 2:
                       dataArray[i][j]=new Double(d[i][j]);
                       break;
                  case 3:
                       dataArray[i][j]=new Double(d[i][j]);
                       break;
                  case 4:
                       dataArray[i][j]=new Double(d[i][j]);
                       break;
                  case 5:
                       dataArray[i][j]=new Double(d[i][j]);
                       break;
                 }//end switch
           }
       }//end for loops
   }

     public void printDataArray(){
       for(int i=0;i<dataArray.length;i++){
           for(int j=0;j<dataArray[i].length;j++){
               System.out.printf("%s ", dataArray[i][j]);
           }
           System.out.println("");
       }
   }

     public void printDateArray(){
       for(int i=0;i<dateArray.length;i++){
           System.out.println(dateArray[i]);
       }
   }
}

package myProva;

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import java.io.*;

public class ProvaJFrame extends javax.swing.JFrame {

    /** Creates new form ProvaJFrame */
    public ProvaJFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        LoadDataButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        LoadDataButton1.setText("Load Data");
        LoadDataButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LoadDataButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(53, 53, 53)
                .addComponent(LoadDataButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(450, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(118, 118, 118)
                .addComponent(LoadDataButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(233, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void LoadDataButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                                
JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new TxtFileFilter());
    int returnVal = fileChooser.showOpenDialog(this);
    if(returnVal == JFileChooser.APPROVE_OPTION){
        File myFile = fileChooser.getSelectedFile();
        FileImport obj1 = new FileImport(myFile);
        System.out.println(obj1.checkIsFile());
      System.out.println(obj1.numberOfLines());

      obj1.importToArray();
      obj1.printArray();

      System.out.println("--------------------------------------");
        }
    }

    private class TxtFileFilter extends FileFilter{
        public boolean accept(File file){
            if(file.isDirectory()) return true;
            String fname = file.getName();
            return fname.endsWith("txt");
        }
        public String getDescription(){
        return "txt file";
    }
    }                                               

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ProvaJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton LoadDataButton1;
    // End of variables declaration                   

}

无法找出我获得NullPointerException的原因。我还想调用主要方法buildDataArrayprintDataArray()buildDateArrayprintDateArray()

要导入的Txt数据如下

20100415,6286.63,6310.76,6249.74,6291.45,31402600
20100416,6264.65,6305.4,6162.84,6180.9,80519400
20100419,6158.6,6190.86,6140.38,6162.44,38311800
20100420,6193.5,6267.54,6172.57,6264.23,42345100
20100421,6280.54,6281.38,6229.18,6230.38,46312400

谢谢!

2 个答案:

答案 0 :(得分:4)

初始化实例变量时,您正在调用numberOfLines

double[][]dataArray = new double [numberOfLines()][5];//Array for double data
Date[]dateArray = new Date[numberOfLines()];//Array for date(calendar)

numberOfLines使用您在构造函数中设置的fileToImport

public FileImport(File myFile) {
    fileToImport = myFile;
}//constructor for fileToImport field

但是这些变量在构造函数执行之前被初始化,因此fileToImport实际上是空的 一种可能的解决方案:在赋值后立即在构造函数中移动初始化。

PS帖子下方有“编辑”按钮:您可以使用它来添加堆栈跟踪或任何其他信息。比发表十几条评论容易得多。

答案 1 :(得分:1)

当您在Java中获得异常时,会生成堆栈跟踪。堆栈跟踪的第一行是异常消息,第二行以at开头,显示了代码中引发此异常的确切位置(类,方法是源中的行号)文件)。

查看此位置,并尝试查找异常发生的原因。在99%的情况下,NullPointerException意味着您正在尝试调用方法或访问空引用上的字段(即从未初始化的变量)。

因此,请尝试自己查找,或者给我们堆栈跟踪,并告诉您行号指向代码中的哪一行,以便我们为您提供更多帮助。