我對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