我在阅读文件时遇到问题,我可以让它读取所有行,但是使用下一行中的第一条信息,或者它会在末尾添加一个空白行,混淆构造函数数组
import java.io.*;
import java.util.*;
public class StudentMain {
/**
* @param args
*/
//(String fn, String ln, String pn, int id, boolean ft, int phn, boolean lj, String con)
//array and sorting variables
public static studentConstructor[] stuArrayOrig;
private static String[] stuArrayIdSort;
private static String[] stuArrayNameSort;
private static int i = 0;
private static int lineCount = 0;
private static int nElms = 0;
//studentConstructor variables
public static String fn; //First Name
public static String ln; //Last Name
public static String pn; //Preferred Name
public static int id; //Student Id Number
public static boolean ft;//Full-time Boolean
public static int phn; //Student Phone Number
public static boolean lj;//Loving java Boolean
public static String con;//Continuing
public static void StuRead()
{
Scanner inFile = null;
try
{
inFile = new Scanner
(new FileReader("Res/students.txt"));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
System.out.println("File Not Found");
e.printStackTrace();
}
while (inFile.hasNextLine()){
inFile.useDelimiter(",|\\n"); //breaks the lines into single info
ln = inFile.next();
System.out.println(ln);
fn = inFile.next();
System.out.println(fn);
pn = inFile.next();
System.out.println(pn);
id = inFile.nextInt();
System.out.println(id);
ft = inFile.nextBoolean();
System.out.println(ft);
phn = inFile.nextInt();
System.out.println(phn);
lj = inFile.nextBoolean();
System.out.println(lj);
con = inFile.next();
System.out.println(con);
studentConstructor st = new studentConstructor(ln, fn, pn, id, ft, phn, lj, con);
System.out.println(st);
//System.out.println("LINE");
stuArrayOrig[lineCount] = st;
inFile.nextLine();
System.out.println(stuArrayOrig[lineCount]);
lineCount++;`
文件输入示例:
Angelon Arouca,Lucas,,1472429,TRUE,407514687,TRUE,Confirmed
Cordovilla,Wilbert,,1472430,TRUE,407514688,FALSE,Confirmed
Danks,Joshua,,1472431,TRUE,407514689,TRUE,Confirmed
我得到的输出:
Angelon Arouca
Lucas
1472429
true
407514687
true
Confirmed
studentConstructor@29ba92bb
Exception in thread "main" java.lang.NullPointerException
at StudentMain.StuRead(StudentMain.java:73)
at StudentApp.main(StudentApp.java:10)
谁能看到我哪里出错?
答案 0 :(得分:2)
您从未初始化stuArrayOrig
,因此它是null
,尝试访问它会导致NullPointerException
。
一旦接近将其初始化为某个“安全”的大值:
public static studentConstructor[] stuArrayOrig = new studentConstructor[100];
但是,使用自我增长的ArrayList
:
public static List<studentConstructor> stuArrayOrig = new ArrayList<>();