我不断收到错误消息Error: java.lang.NullPointerException at runtime
。显然我明白这表明当我引用一些具有空值的变量时它应该有一些值。最好向您展示代码,以便将其置于上下文中。
public class MarathonAdmin
{
private List<Runner> runners;
/**
* Constructor for objects of class MarathonAdmin
*/
public MarathonAdmin()
{
// initialise instance variables
List<Runner> runners = new ArrayList<>();
}
public void readInRunners()
{
String pathName = OUFileChooser.getFilename();
File aFile = new File(pathName);
Scanner bufferedScanner = null;
try
{
String runnerName;
int runnerAge;
String ageGroup;
Scanner lineScanner;
String currentLine;
bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));
while (bufferedScanner.hasNextLine())
{
currentLine = bufferedScanner.nextLine();
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
runnerName = lineScanner.next();
runnerAge = lineScanner.nextInt();
Runner runnerObject = new Runner();
if (runnerAge < 18)
{
ageGroup = "junior";
runnerObject.setAgeGroup(ageGroup);
}
else
if (runnerAge > 54)
{
ageGroup = "senior";
runnerObject.setAgeGroup(ageGroup);
}
else
{
ageGroup = "standard";
runnerObject.setAgeGroup(ageGroup);
}
runnerObject.setName(runnerName);
runners.add(runnerObject);
}
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
finally
{
try
{
bufferedScanner.close();
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
}
}
创建类实例的测试代码是:
MarathonAdmin ma = new MarathonAdmin();
ma.readInRunners();
有一个名为Runners
的类正在使用其协议进行设置。该类编译但ma.readInRunner();
消息以错误结束。程序要运行的文本文件没有错误。
我对编程有点新鲜,因此很难解决问题。希望有人可以帮助我。
答案 0 :(得分:1)
在构造函数中它应该是
public MarathonAdmin()
{
// initialise instance variables
this.runners = new ArrayList<>();
}
而不是
public MarathonAdmin()
{
// initialise instance variables
List<Runner> runners = new ArrayList<>();
}
答案 1 :(得分:0)
问题是您已经创建了一个Try-catch块,但是在catch部分中你没有打印stacktrace ,请参阅:
catch (Exception anException)
{
System.out.println("Error: " + anException); // just prints: Error: java.lang.NullPointerException
}
改进此catch块以进行调试,例如:
catch (Exception e) {
e.printStackTrace(); //prints the full stacktrace
}
现在你应该得到一个完整的堆栈跟踪,它也会显示行号,你可以自己调试它; - )
实际上你可能应该删除那些try-catch块。