首页 \ 问答 \ 从Java中读取文件和空指针异常(Reading From File in Java and Null Pointer Exception)

从Java中读取文件和空指针异常(Reading From File in Java and Null Pointer Exception)

我是java的新手,我遇到了一个我自己无法解决的问题。 我用Google搜索了异常,但问题太具体了,据我所知,所以我发现自己在这里。 这是我的问题。

我有一个名为Student的类,它有一个不合格的数据成员及其get / set方法:

private String studentNumber;
private String firstName;
private String lastName;
private int age;
private String gender;
private String country;

然后我创建了一个实例数组:

Student studentList[] = new Student(10);

我有一个数据库(文本文件)作为休息

081935 Cengiz rrrrr Male 21 Turkey
082935 Ayşe aaaaa Female 22 England
083935 Onur bbbbb Male 23 Germany
084935 Fatma ccccc Female 24 Cyprus
085935 Ali dddd Male 21 China
086935 Zehra eeee Female 22 Denmark
087935 Murat ffff Male 25 France
088935 Selin ggggg Female 26 Japan
086935 Cengiz hhhh Male 20 Korea
080935 Damla qqqqqq Female 19 Iran

我想要做的是将所有这些信息传递给我的类实例,并尝试实现这一目标:

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

public class StudentTracker  {

    private static int counter = 0;
    private static Student studentList[];

    public static void readFromFile() throws FileNotFoundException {
        File file = new File("Database.txt");
        Scanner scanner = new Scanner(new FileReader(file));
        try {
              while (scanner.hasNextLine()){
                processLine(scanner.nextLine());
              }
        } finally {
            scanner.close();
        }
    }


    public static void processLine(String line) {
        Scanner scanner = new Scanner(line);
        scanner.useDelimiter(" ");
        if (scanner.hasNext()) {
          studentList[counter].setStudentNumber(scanner.next());
          studentList[counter].setFirstName(scanner.next());
          studentList[counter].setLastName(scanner.next());
          studentList[counter].setGender(scanner.next());
          studentList[counter].setAge(Integer.parseInt(scanner.next()));
          studentList[counter].setCountry(scanner.next());      
          counter++;
        }
        else {
            System.out.println("Empty or invalid line. Unable to process.");
        }
      }

    public static void main(String[] args) throws FileNotFoundException {

        studentList = new Student[10];
        readFromFile();
        for(int i = 0; i < 10; i++) {
            System.out.printf(studentList[i].getStudentNumber(), " ",
                              studentList[i].getFirstName());

        }

    }

}

但它会导致以下错误:

Exception in thread "main" java.lang.NullPointerException
    at StudentTracker.processLine(StudentTracker.java:28)
    at StudentTracker.readFromFile(StudentTracker.java:16)
    at StudentTracker.main(StudentTracker.java:68)

顺便说一句找不到像C-scanf这样的函数,它获取输入直到第一个空格,所以我找到另一种解析字符串的方法

readFromFile()和processLine函数,但我不确定它们是否按预期工作。

先谢谢你


I'm pretty new to java and I've got a problem that I couldn't solve by myself. I googled the exception but problem is too specific as far as I can understand so I find myself here. Here is my problem.

I have a class called Student which has fallowing data members and their get/set methods:

private String studentNumber;
private String firstName;
private String lastName;
private int age;
private String gender;
private String country;

and I created an array of instances as fallowing:

Student studentList[] = new Student(10);

I got a database(a text file) as fallowing

081935 Cengiz rrrrr Male 21 Turkey
082935 Ayşe aaaaa Female 22 England
083935 Onur bbbbb Male 23 Germany
084935 Fatma ccccc Female 24 Cyprus
085935 Ali dddd Male 21 China
086935 Zehra eeee Female 22 Denmark
087935 Murat ffff Male 25 France
088935 Selin ggggg Female 26 Japan
086935 Cengiz hhhh Male 20 Korea
080935 Damla qqqqqq Female 19 Iran

What I'm trying to do is getting all these informations to my class instances and I try to achieve this is fallowing:

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

public class StudentTracker  {

    private static int counter = 0;
    private static Student studentList[];

    public static void readFromFile() throws FileNotFoundException {
        File file = new File("Database.txt");
        Scanner scanner = new Scanner(new FileReader(file));
        try {
              while (scanner.hasNextLine()){
                processLine(scanner.nextLine());
              }
        } finally {
            scanner.close();
        }
    }


    public static void processLine(String line) {
        Scanner scanner = new Scanner(line);
        scanner.useDelimiter(" ");
        if (scanner.hasNext()) {
          studentList[counter].setStudentNumber(scanner.next());
          studentList[counter].setFirstName(scanner.next());
          studentList[counter].setLastName(scanner.next());
          studentList[counter].setGender(scanner.next());
          studentList[counter].setAge(Integer.parseInt(scanner.next()));
          studentList[counter].setCountry(scanner.next());      
          counter++;
        }
        else {
            System.out.println("Empty or invalid line. Unable to process.");
        }
      }

    public static void main(String[] args) throws FileNotFoundException {

        studentList = new Student[10];
        readFromFile();
        for(int i = 0; i < 10; i++) {
            System.out.printf(studentList[i].getStudentNumber(), " ",
                              studentList[i].getFirstName());

        }

    }

}

but it gives fallowing error:

Exception in thread "main" java.lang.NullPointerException
    at StudentTracker.processLine(StudentTracker.java:28)
    at StudentTracker.readFromFile(StudentTracker.java:16)
    at StudentTracker.main(StudentTracker.java:68)

by the way couldn't find a function like C-scanf which gets the input until first white space so I find another way to parse the strings from line with

readFromFile() and processLine functions but I'm not sure if they're workig as intended.

Thank you in advance


原文:https://stackoverflow.com/questions/9791837
更新时间:2022-05-09 22:05

最满意答案

IntentServiceContext的子类(就像ActivityApplication和许多其他Android类一样)。 当然,您可以从IntentService创建SharedPreferences 。 它将看到与应用程序中的任何Activity或其他Context相同的SharedPreferences值。 (这就是为什么它被称为共享 。)你只需要确保在一个上下文中apply()commit()在首选项编辑器中进行的更改,以便在其他地方看到更改。 这些都包含在文档中


An IntentService is a subclass of Context (just as are Activity, Application, and many other Android classes). So of course you can create a SharedPreferences from an IntentService. It will see the same SharedPreferences values that any Activity or other Context in your application would see. (That's why it's called shared.) You just have to make sure that you apply() or commit() changes made in the preference's editor in one context for the changes to be seen in other places. This is all covered in the docs.

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)