回 帖 发 新 帖 刷新版面

主题:为什么出现错误:java.lang.NullPointerException

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


public class Exercise4_2 {

    /**
     * @param args
     */
    private static int[] a;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        if(args.length!=1){
            System.out.println("Usage: java Exercise4_2 filename");
            System.exit(1);
        }
        try{
            BufferedReader in=new BufferedReader(new FileReader(args[0]));
            String line;
            
            int i=0;
            int sum=0;
            while((line=in.readLine())!=null){
                a[i++]=Integer.parseInt(line);
            }
            for(int j=0;j<a.length;j++){
                sum+=a[i];
            }
            System.out.println("The average number is "+sum/a.length);
            System.out.println("The total number is"+a.length);
        }catch(IOException e){
            e.printStackTrace();
        }
        
    }

}

回复列表 (共5个回复)

沙发

试试这个

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class ListFiles
{
    public static void main( String [ ] args )
    {
        if( args.length == 0 )
            System.out.println( "No files specified" );
        else
            listFile( args[ 0 ] );
    }

    public static void listFile( String fileName )
    {
        FileReader theFile;
        BufferedReader fileIn = null;
        String oneLine;

        System.out.println( "FILE: " + fileName );
        try
        {
            theFile = new FileReader( fileName );
            fileIn  = new BufferedReader( theFile );
            while( ( oneLine = fileIn.readLine( ) ) != null )
                System.out.println( oneLine );
        }
        catch( IOException e )
          {  System.out.println( e ); }
        finally
        {
            // Close the stream
            try
            {
                if(fileIn != null )
                    fileIn.close( );
            }
            catch( IOException e )
              { }
        }
    }
}

板凳

楼上的跟我的代码有区别吗?

3 楼

我运行没有出错哦,楼主看看是不是搞错了

4 楼

虽然JAVA没有指针的概念,但是我还是要说,这是空指针异常,你仔细坚持下你哪传入值为空了,自己检查,这样印象深

5 楼

我觉得是你那个数组没有进行初始化,所以会提示这个错误改了就好了

我来回复

您尚未登录,请登录后再回复。点此登录或注册