首页 > 解决方案 > 使用scanner.hasNext()时出现Java NullPointerException;

问题描述

我想出了以下代码来从文件中读取信息:

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

public class Reader {

    private Scanner s;

    public void openFile() {
        try {
            s = new Scanner(new File("file.txt"));
        } catch (Exception e) {
            System.out.println("File not found. Try again.");
        }
    }

    public void readFile() {
        while (s.hasNext()) {
            String a = s.next();
            String b = s.next();
            String c = s.next();
            int d = s.nextInt();
            int e = s.nextInt();
            int f = s.nextInt();
    }

    public void closeFile() {
        s.close();
    }

}

但是,我在 ( while (s.hasNext()) ) 行上收到 NullPointer 错误并且找不到解决方案。

我在 Eclipse 中工作,并且我正在读取的文件已正确导入到项目中,因此这应该不是问题。

编辑:

我访问方法的方式:

public class Tester {

    public static void main(String[] args) {

        Reader read = new Reader();

        read.openFile();
        read.readFile();
        read.closeFile();

    }

}

标签: javanullpointerexceptionjava.util.scanner

解决方案


根据 NPE 抛出的语句,while (s.hasNext())很可能s是空指针,您可以System.out.println(s);在该语句之前添加以双重确认。

而对于sis的原因null,有两个可能的原因:

  1. openFile你之前没有调用readFile
  2. 打开文件时抛出异常。这s只是一个声明,还没有指向任何对象。

null也许为了更好的实践,您可以在调用其方法之前断言实例是否存在。根据我的理解,这readFile取决于 的结果openFile,也许您可​​以将返回值设置openFile为布尔值,并在进一步打开文件操作之前检查返回值。无法读取甚至无法打开的文件,对吧?

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

public class Reader {

    private Scanner s;

    public boolean openFile() {
        try {
            s = new Scanner(new File("file.txt"));
            return true;
        } catch (Exception e) {
            System.out.println("File not found. Try again.");
            return false;
        }
    }

    public void readFile() {
        while (s.hasNext()) {
            String a = s.next();
            String b = s.next();
            String c = s.next();
            int d = s.nextInt();
            int e = s.nextInt();
            int f = s.nextInt();
     }
}

调用者可以执行如下操作:

Reader reader = new Reader();
if (reader.openFile())
    reader.readFile();

推荐阅读