我的代码出现问题。它编译,但我遇到了一个扫描仪打印null的问题多少次是由于我放置的驱动程序类末尾的for-each循环。目标是从文本文件中读取名字,姓氏和邮政编码字符串,并使用for-each循环打印输入。我不确定我做错了什么。
输入文件的示例行将读取如下内容:
名字:Joe姓:Jimbob邮政编码:55555
编辑:.txt文件中有25行代表一个包含25个Person对象的数组。我的坏!
这是我到目前为止简化的内容:
用于打印数据和驱动程序的驱动程序类:
... throws IO Exception
String firstname = " ";
String lastname = " ";
String postalcode = " ";
File file = new File("input.txt");
Scanner fileScan = new Scanner(file);
Person person[] = new Person[25]; // An array of 25 Person objects see Person class
while(fileScan.hasNext()) //Error was generated here at Line 20 originally N. Pointer Exception not too sure how to regenerate it
{
String token= fileScan.next(); //Token to scan for each word and match it with the string before it
if(token.equals("Firstname: "))
{
firstname = fileScan.next();
}
else if(token.equals("Lastname: "))
{
lastname = fileScan.next();
}
else if(token.equals("Postalcode: "))
{
postalcode = fileScan.next();
}
for(Person info : person) // Generates null on execution supposed to print Array
{
System.out.println(info); // Prints null not exactly sure why
}
Person类可以看到Person对象的创建位置:
public class Person
{
private String firstname, lastname, postalcode;
public Person(String firstname, String lastname, String postalcode)
{
this.firstname = firstname;
this.lastname = lastname;
this.postalcode = postalcode;
}
public String toString()
{
return(firstname + " " + lastname +" "+ postalcode);
}
}
答案 0 :(得分:1)
关闭while循环后需要使用for循环。类似的东西:
while(fileScan.hasNext())
{
String token= fileScan.next();
if(token.equals("Firstname: "))
{
firstname = fileScan.next();
}
else if(token.equals("Lastname: "))
{
lastname = fileScan.next();
}
else if(token.equals("Postalcode: "))
{
postalcode = fileScan.next();
}
}
for(Person info : person)
{
System.out.println(info);
}
如果文件中的人数少于25人,仍然会打印空值。您也可以尝试:
for(Person info : person)
{
if(info != null){
System.out.println(info);
}
}
编辑:
注意到它看起来好像你没有将人员添加到数组中?像
person[2] = new Person(firstName, lastname, postalcode); //etc