为什么这会给我一个NullPointerException?

时间:2014-12-14 21:43:42

标签: java nullpointerexception

String line = "";
BufferedReader f = new BufferedReader(new FileReader("test.txt"));
StringTokenizer x = new StringTokenizer(f.readLine());
int n = Integer.parseInt(x.nextToken());
for(int i = 0; i < n; i++)
{
    if(line == null)
        break;
    else
        line = f.readLine();

    StringTokenizer st = new StringTokenizer(line);

    xCoord.add(Integer.parseInt(st.nextToken()));
    yCoord.add(Integer.parseInt(st.nextToken()));
}

这是代码。不知道为什么我会得到例外。我有while循环设置来检查行是否为空。

档案:

5
0 1
5 4
9 8
0 1

StringTokenizer st = new StringTokenizer(line);

获取例外
Exception in thread "main" java.lang.NullPointerException
at java.util.StringTokenizer.<init>(StringTokenizer.java:199)
at java.util.StringTokenizer.<init>(StringTokenizer.java:236)
at Problems.ProblemOne.main(ProblemOne.java:45)

Java结果:1

1 个答案:

答案 0 :(得分:3)

在您的代码中,您有声明:

if(line == null)
            break;
        else
            line = f.readLine();

在最后一段代码之后,在'else'子句中,line可能等于null,因为您刚尝试从文件中读取另一行。拥有类似的东西可能会更好:

line = f.readLine();
if(line == null) break;

基于文件内容:

4 
0 5 
7 3 
11 -6 
0 2

以下示例代码可以正常运行:

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

public class AlanTest
{
    public static void main(String[] args) throws FileNotFoundException, IOException
    {
        String line = "";
        BufferedReader f = new BufferedReader(new FileReader("test.txt"));
        StringTokenizer x = new StringTokenizer(f.readLine());
        int n = Integer.parseInt(x.nextToken());
        for(int i = 0; i < n; i++)
        {
            line = f.readLine();
            if(line == null) break;

            StringTokenizer st = new StringTokenizer(line);
            int xCoord = Integer.parseInt(st.nextToken());
            int yCoord = Integer.parseInt(st.nextToken());
            System.out.format("%d %d%n", xCoord, yCoord);
        }
    }
}

绝对需要知道你在哪里获得例外。