如何在我的代码中修复空指针异常?

时间:2017-03-10 20:49:15

标签: java nullpointerexception

我正在尝试读取文件并将文件中的每一行设置为我所创建的对象OS_Process的参数,然后将这些进程放在linklist队列中。但是,我不断得到nullpointerexception。数据文件如下所示。每个新的流程数据都在新的一行上。

3 //counter
1 3 6 //process 1 data
3 2 6 //process 2 data
4 3 7 //process 3 data

这是我的代码

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

    public class OS_Scheduler
    {
    public static void main(String[] args)
    {
        Queue<OS_Process> jobs = new LinkedList<OS_Process>();

        try
        {
            System.out.print("Enter the file name: ");
            Scanner file = new Scanner(System.in);
            File filename = new File(file.nextLine());

            OS_Process proc = null;
            String s = null;
            int a = 0, p = 0, b = 0;
            BufferedReader input = new BufferedReader(new FileReader(filename));
            StringTokenizer st = new StringTokenizer(s);
            int count = Integer.parseInt(st.nextToken());
            while ((s = input.readLine()) != null)
            {
                st = new StringTokenizer(s);
                a = Integer.parseInt(st.nextToken());
                p = Integer.parseInt(st.nextToken());
                b = Integer.parseInt(st.nextToken());
                proc = new OS_Process(a, p, b, 0);
                jobs.add(proc);
            }
            input.close();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }
}

1 个答案:

答案 0 :(得分:2)

您有一个NullpointerException,因为您已设置String s = null;,然后调用等于StringTokenizer stz = new StringTokenizer(s);的{​​{1}},这将获得Nullpointer。

您不需要知道StringTokenizer stz = new StringTokenizer(null);行,因为count - 循环遍历文件中的所有行,如果到达文件末尾则会停止 所以更新您的代码如下:

while

或者如果你想使用String s = input.readLine();//read first line to get rid of it if(s == null){ //File is empty -> abort System.out.println("The file is empty"); System.exit(0); } int a = 0, p = 0, b = 0; StringTokenizer st; while ((s = input.readLine()) != null) {...} ,你可以这样做:

count