我对Java很新,我遇到了一个我自己无法解决的问题。我搜索了例外情况,但只要我能理解,问题就太具体了,所以我在这里找到了自己。这是我的问题。从Java文件和空指针中读取异常
我有一类称为学生具有休耕数据成员和他们的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
我想要做的是获取所有这些informati附件我的类的实例,我尝试实现这一目标是休耕:
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函数,但我不确定他们是否按预期工作。
先谢谢您
scanner.nextLine() – 2012-03-20 17:26:33