我有一个文本文件,其中包含我的计划中的所有人员(职员、雇员、讲师和学生)及其相关信息(具体取决于人员类型)。我有一个包含所有方法的目录类,以及一个作为接口(interface)类的 DirectoryServer。
我的添加方法无法正常工作,因为当我添加新类型的人员时,当我尝试更新文本文件时,它会将前四个字段设置为空。此外,在我添加一个新人然后尝试查找(查找是我的程序中的另一种方法)后,它说该名称不在目录中,即使它在目录中。第四个字段之后的字段是用户输入的内容,它正确显示在我的文本文件中。
这是我的目录类中的添加方法和关闭方法:
public boolean add(Person obj) throws IOException {
boolean added = true;
String s = obj.toString();
dir[directorySize++] = s;
return added;
}
public void closeDirectory() {
directoryDataIn.close();
PrintStream directoryDataOut = null;
try {
directoryDataOut = new PrintStream(directoryFile);
}
catch (FileNotFoundException e) {
System.out.printf("File %s not found, exiting!", directoryFile);
System.exit(0);
}
String originalDirectory[] = {"Staff 77778 Julie Chang Registrar","Adjunct 19778 Mike Thompson CS mtxxx@gmail.com GITC2400", "Staff 30041 Anne Mathews Security","Junior 98444 Serene Murray Math smyyy@gmail.com", "Freshman 98772 Bob Mathew CS bmyyy@gmail.com","Professor 19010 Joan Berry Math jbxxx@gmail.com GITC2315C","Professor 19871 Aparna Khat CS akxxx@gmail.com GITC1400","Adjunct 18821 Hari Mentor Physics hmxxx@gmail.com CK231","Staff 20112 Jim George Plant","Junior 68339 Tom Harry CS thyyy@gmail.com","Senior 78883 Vince Charles IT vcyyy@gmail.com","Freshman 87777 Susan Han EE shyyy@gmail.com","Senior 88888 Janki Khat IE jkyyy@gmail.com","Staff 5555 Aparna Sen Plant","Senior 66663 Jill Kaley it jk@jk.com","Staff 77777 Joe Batra plumbing","Staff 33333 Jim Natale Plumbing"};
if (originalDirectory == dir) //do not update text file if no changes were made
System.exit(0);
else
for (int i = 0; i < directorySize; i++)
directoryDataOut.println(dir[i]);
directoryDataOut.close();
}
这就是我的文本文件的摘录应该是什么样的:
Senior 88888 Janki Khat IE jkyyy@gmail.com
但结果是这样的:
null null null null MATH rwood@njit.edu
我该如何解决这个问题? 由于某种原因,这个错误的输出今天才出现。上周,当一切正常时,我关闭并保存了所有类(class)文件。
这是我的 Person 类
public class Person {
private String Position;
private String UCID;
private String FirstName;
private String LastName;
public Person(String Position, String UCID, String FirstName, String LastName) {
Position = Position;
UCID = UCID;
FirstName = FirstName;
LastName = LastName;
}
public String toString() {
return String.format("%s %s %s %s", Position, UCID, FirstName, LastName);
}
}
这是来 self 的 DirectoryServer 类。在这段代码摘录中,我添加了一位教授或兼职人员。在这一部分之前,我只是使用扫描仪对象逐行获取每个字段的用户输入。
p = new Instructor(pos, ucid, fname, lname, dept, email, office);
try {
d.add(p);
}
catch (Exception e) {
System.out.println("Error, cannot add");
continue;
}
最佳答案
问题出在 Person 类上。您需要使用如下语句:
this.Position = Position
否则你只是将局部变量分配给局部变量。
此外,出于风格原因,您希望实例变量(字段)采用小写。
关于java - 当我添加新人员时,为什么我的目录程序中的添加方法将文本文件中的前四个字段设置为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30032886/